咨询:在C++中使用Microsoft SEAL的BFV方案创建打包密文数组
在C++中使用Microsoft SEAL BFV创建打包密文数组的解决方案
优先方案:使用std::vector管理密文数组
Microsoft SEAL的Ciphertext是具备拷贝/移动语义的类,直接用STL容器(比如std::vector)是最安全省心的方式,完全不需要手动处理指针和内存分配,能避免野指针、内存泄漏等问题。
以下是完整可运行代码示例:
#include <seal/seal.h> #include <vector> using namespace seal; int main() { // 配置BFV参数,指定8192个槽位 EncryptionParameters parms(scheme_type::bfv); const size_t poly_modulus_degree = 8192; parms.set_poly_modulus_degree(poly_modulus_degree); parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree)); // 配置适合打包的明文模数(20位,适配8192槽位) parms.set_plain_modulus(PlainModulus::Batching(poly_modulus_degree, 20)); // 创建SEAL上下文 SEALContext context(parms); // 初始化密钥、加密器、打包器 KeyGenerator keygen(context); PublicKey public_key; keygen.create_public_key(public_key); Encryptor encryptor(context, public_key); BatchEncoder batch_encoder(context); // 创建包含10个Ciphertext的数组 std::vector<Ciphertext> ciphertext_array(10); // 准备测试用的打包明文(8192个槽位全填1) std::vector<uint64_t> plain_data(poly_modulus_degree, 1); Plaintext plain; batch_encoder.encode(plain_data, plain); // 加密填充每个密文 for (auto &cipher : ciphertext_array) { encryptor.encrypt(plain, cipher); } // 后续可对ciphertext_array执行同态加法、乘法等操作 // 示例:第一个密文加第二个密文 Ciphertext result; Evaluator evaluator(context); evaluator.add(ciphertext_array[0], ciphertext_array[1], result); return 0; }
手动指针方案(不推荐)
如果一定要使用指针,必须确保每个Ciphertext对象被正确初始化,并且使用完后手动释放内存:
#include <seal/seal.h> using namespace seal; int main() { // 省略参数配置、上下文初始化、密钥组件创建步骤(同上面的代码) // 动态分配10个Ciphertext对象的数组 Ciphertext *ciphertext_array = new Ciphertext[10]; // 循环加密填充每个密文 for (int i = 0; i < 10; ++i) { encryptor.encrypt(plain, ciphertext_array[i]); } // 使用数组执行操作... // 必须手动释放内存,避免泄漏 delete[] ciphertext_array; return 0; }
常见错误原因
你之前用指针出错,大概率是因为:
- 未初始化指针就直接使用(比如
Ciphertext *ptr;后直接赋值,此时ptr是野指针) - 未将
Ciphertext关联到有效的SEAL上下文(SEAL的加密类必须依赖正确初始化的上下文才能工作) - 手动内存管理时遗漏了释放操作,或者释放方式错误(比如用
delete而不是delete[]释放数组)
内容的提问来源于stack exchange,提问作者Coder Man
相关产品推荐
相关产品推荐

