HElib-1 : 简单的密文相加

编译好HElib库后,直接在src文件夹下进行相关测试文件的编写。
本文翻译自:
https://mshcruz.wordpress.com/2016/06/17/2-3-using-helib/

该文章利用HElib库实现两个数相加。

首先,看一些参数的初始化:

long p = 1021; // Plaintext base [default=2], should be a prime number
long r = 1;    // Lifting [default=1]
long L = 16;   // Number of levels in the modulus chain [default=heuristic]
long c = 3;    // Number of columns in key-switching matrix [default=2]
long w = 64;   // Hamming weight of secret key
long d = 0;    // Degree of the field extension [default=1]
long k = 128;  // Security parameter [default=80]
long s = 0;    // Minimum number of slots [default=0]
long m = FindM(k,L,c,p, d, s, 0); //Specific modulus

之后,创建一个FHEcontext对象来保存所有参数:

FHEcontext context(m, p, r);
buildModChain(context, L, c);

创建一个多项式用来加密:

ZZX G = context.alMod.getFactorsOverZZ()[0];

利用context来生成公钥和私钥:

FHESecKey secretKey(context);
const FHEPubKey& publicKey = secretKey;
secretKey.GenSecKey(w);

加密,利用Ctxt类来保存密文:

Ctxt ctx1(publicKey);
Ctxt ctx2(publicKey);

publicKey.Encrypt(ctx1, to_ZZX(2));
publicKey.Encrypt(ctx2, to_ZZX(3));

密文运算:

Ctxt ctSum = ctx1;
ctSum += ctx2;

创建一个多项式来保存解密的结果:

ZZX ptSum;
secretKey.Decrypt(ptSum, ctSum);

以下是完整的代码,编写文件SimpleFHESum.cpp:

#include "FHE.h"
#include <iostream>

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;


    Ctxt ctxt1(publicKey);
    Ctxt ctxt2(publicKey);

    publicKey.Encrypt(ctxt1, to_ZZX(2));  //encrypt the value 2
    publicKey.Encrypt(ctxt2, to_ZZX(3));  //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 << "2 + 3 = " << ptSum[0] << endl;

    return 0;

之后生成可执行文件:
make SimpleFHESum_x

猜你喜欢

转载自blog.csdn.net/qi_1221/article/details/80065714