已经成功安装了gmp和ntl,接下来安装和调试HElib。
从GitHub上拉取项目,注册账号后通过这里https://github.com/homenc/HElib下载,可以先右上角Fork到自己的账号下,然后通过Git下载到本地。
先安装Git:
sudo apt-get install git
点“Fork”就在自己的账号下克隆了一个HElib仓库,然后从自己的账号下clone(其实可以直接从他人的账号下clone,但是只有从自己的账号下clone才可以推送修改):
git clone https://github.com/wangjinglin0721/HElib.git
这样就可以在主目录下看到HElib文件夹,项目克隆完成。
在HElib目录的src文件夹下对Makefile文件进行操作:
# Change the Makefile as the following:
Line 19: COPT = -g -O2 -std=c++11 -march=native
Line 85: #(Insert the following contents)
install:
cp -p fhe.a /usr/local/lib/libfhe.a
chmod a+r /usr/local/lib/libfhe.a
rm -rf /usr/local/include/fhe
mkdir -m 755 /usr/local/include/fhe
cp -p *.h /usr/local/include/fhe/
chmod -R a+r /usr/local/include/fhe
修改后保存文件,在该目录下make:
$ make
$ make check
$ sudo make install
对文件执行 make 操作,此时编译产生了许多的.o 文件, 与此同时我们还可以在 src 文件夹中发现自动生成了 fhe.a 的静态链接库。
make check可以产生可执行文件_x,(但是由于电脑配置问题,部分文件无法运行成功,卡住了,所以强行跳过这步直接安装。。。)
接下来进行测试,任意一个 src 文件夹下的cpp文件都可以编译运行,例如Test_General.cpp:
g++ -pthread -g -O2 -std=c++11 -march=native -DFHE_THREADS -DFHE_BOOT_THREADS -o Test_General_x Test_General.cpp fhe.a -lntl -lgmp -lm
生成Test_General_x可执行文件。
运行程序:
./Test_General_x
编写程序时,以防出错,要加头文件和命名空间,以test02为例:
#include
#include
#include "FHE.h"
#include "timing.h"
#include "EncryptedArray.h"
#include
#include
#include
#include
#include "ArgMap.h"
#include "fhe_stats.h"
#include
using namespace helib;
using namespace NTL;
using namespace std;
int main(int argc, char **argv)
{
long p = 1021;
long r = 1;
long L = 4;
long c = 2;
long k = 80;
long s = 0;
long d = 0;
long w = 64;
cout << "finding m..." << flush;
long m = FindM(k,L,c,p,d,s,0);
cout << "m = "<< m << endl;
cout << "Initializing context..." << flush;
FHEcontext context(m,p,r); //initialize context
buildModChain(context, L, c); //modify the context
cout << "OK!" << endl;
cout << "Creating polynomial..." << flush;
ZZX G = context.alMod.getFactorsOverZZ()[0]; //creates the polynomial used to encrypted the data
cout << "OK!" << endl;
cout << "Generating keys..." << flush;
FHESecKey secretKey(context); //construct a secret key structure
const FHEPubKey& publicKey = secretKey; //An "upcast": FHESecKey is a subclass of FHEPubKey
secretKey.GenSecKey(w); //actually generate a secret key with Hamming weight w
cout << "OK!" << endl;
int a,b;
cin >> a >> b;
Ctxt ctxt1(publicKey);
Ctxt ctxt2(publicKey);
publicKey.Encrypt(ctxt1, to_ZZX(a)); //encrypt the value 2
publicKey.Encrypt(ctxt2, to_ZZX(b)); //encrypt the value 3
Ctxt ctSum = ctxt1; //create a ciphertext to hold the sum and initialize it with Enc(2)
ctSum += ctxt2;
ZZX ptSum; //create a ciphertext to hold the plaintext of the sum
secretKey.Decrypt(ptSum, ctSum);
cout << a << " + " << b << " = " << ptSum[0] << endl;
return 0;
}
代码参考:https://blog.csdn.net/qi_1221/article/details/80065714