2021SC@SDUSC
目录
介绍
在这一篇文章中,我们主要给出了程序有关的源码,如果在看源码的过程中发现有不懂的地方,可以查看我的上一篇博客 PALISADE开源库(三)CKKS代码分析(一)简单代码步骤介绍 ,如果再不懂的话,可以评论或者私信问我,大家一起加油,fighting!!!
程序源码及注解
#define PROFILE
#include "palisade.h"
using namespace lbcrypto;
int main() {
//指定乘法深度
uint32_t multDepth = 1;
//指定缩放因子的位长
uint32_t scaleFactorBits = 50;
//指定密文中使用的明文槽数
uint32_t batchSize = 8;
//指定基于FHE标准的期望安全级别
SecurityLevel securityLevel = HEStd_128_classic;
//基于指定参数加密上下文
CryptoContext<DCRTPoly> cc =
CryptoContextFactory<DCRTPoly>::genCryptoContextCKKS(
multDepth, scaleFactorBits, batchSize, securityLevel);
std::cout << "CKKS scheme is using ring dimension " << cc->GetRingDimension()
<< std::endl
<< std::endl;
//启用您希望使用的特性
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
//生成加密密钥
auto keys = cc->KeyGen();
//生成重新线性化键
cc->EvalMultKeyGen(keys.secretKey);
//生成旋转键
cc->EvalAtIndexKeyGen(keys.secretKey, {1, -2});
//输入后的编码和加密
vector<double> x1 = {0.25, 0.5, 0.75, 1.0, 2.0, 3.0, 4.0, 5.0};
vector<double> x2 = {5.0, 4.0, 3.0, 2.0, 1.0, 0.75, 0.5, 0.25};
//编码为明文
Plaintext ptxt1 = cc->MakeCKKSPackedPlaintext(x1);
Plaintext ptxt2 = cc->MakeCKKSPackedPlaintext(x2);
//输出编码后的明文
std::cout << "Input x1: " << ptxt1 << std::endl;
std::cout << "Input x2: " << ptxt2 << std::endl;
//加密编码向量
auto c1 = cc->Encrypt(keys.publicKey, ptxt1);
auto c2 = cc->Encrypt(keys.publicKey, ptxt2);
//进行加减乘等操作
//密文相加
auto cAdd = cc->EvalAdd(c1, c2);
//密文相减
auto cSub = cc->EvalSub(c1, c2);
//明文与密文相乘
auto cScalar = cc->EvalMult(c1, 4.0);
//密文相乘
auto cMul = cc->EvalMult(c1, c2);
//密文旋转
auto cRot1 = cc->EvalAtIndex(c1, 1);
auto cRot2 = cc->EvalAtIndex(c1, -2);
//解密和输出
Plaintext result;
//为了更好的输出,我们将cout精度设置为8位十进制数字。
std::cout.precision(8);
std::cout << std::endl
<< "Results of homomorphic computations: " << std::endl;
//解密加法的结果
cc->Decrypt(keys.secretKey, cAdd, &result);
result->SetLength(batchSize);
std::cout << "x1 + x2 = " << result;
std::cout << "Estimated precision in bits: " << result->GetLogPrecision()
<< std::endl;
//解密减法的结果
cc->Decrypt(keys.secretKey, cSub, &result);
result->SetLength(batchSize);
std::cout << "x1 - x2 = " << result << std::endl;
// 解密明文乘密文的结果
cc->Decrypt(keys.secretKey, cScalar, &result);
result->SetLength(batchSize);
std::cout << "4 * x1 = " << result << std::endl;
// 解密密文乘密文的结果
cc->Decrypt(keys.secretKey, cMul, &result);
result->SetLength(batchSize);
std::cout << "x1 * x2 = " << result << std::endl;
// 解密旋转的结果
cc->Decrypt(keys.secretKey, cRot1, &result);
result->SetLength(batchSize);
std::cout
<< std::endl
<< "In rotations, very small outputs (~10^-10 here) correspond to 0's:"
<< std::endl;
std::cout << "x1 rotate by 1 = " << result << std::endl;
cc->Decrypt(keys.secretKey, cRot2, &result);
result->SetLength(batchSize);
std::cout << "x1 rotate by -2 = " << result << std::endl;
return 0;
}
运行结果
总结
这是用PALISADE的主要API来进行CKKS的同态加密解密的简单代码介绍,因为在进行内部代码的介绍之前,我们先弄懂它是做什么的,再了解它是做什么的之后,我们在进行对其源码的挖掘,相信我们在进行挖掘的过程中一定能发现更多的乐趣。