OpenFHE 源码解析:PKE 部分

参考文献:

  1. [ABB+22] Al Badawi A, Bates J, Bergamaschi F, et al. Openfhe: Open-source fully homomorphic encryption library[C]//Proceedings of the 10th Workshop on Encrypted Computing & Applied Homomorphic Cryptography. 2022: 53-63.
  2. openfheorg/openfhe-development
  3. Welcome to OpenFHE’s documentation!
  4. 编译 OpenFHE

OpenFHE 仅支持维度是二的幂次的分圆环,使用的加速手段是 RNS + FFT 而非 RNS + NTT。密文模数是一些字大小素数的乘积,但它们并不用于 NTT 加速,只是用于 RNS 分解罢了。

pke

openfhe

OpenFHE 的头文件,包含了向用户公开的接口。

crypto-context

上下文,用于密码运算的控制。

class CryptoContextImpl,所有 FHE 方案的访问控制,

  • CryptoContextImpl(std::shared_ptr<CryptoParametersBase<Element>> params,
                          std::shared_ptr<SchemeBase<Element>> scheme, SCHEME schemeId = SCHEME::INVALID_SCHEME);
    

    创建参数是 params 的 scheme 上下文

  • void Enable(PKESchemeFeature feature),配置 PKE、SHE、FHE 等等

  • Plaintext MakePlaintext(const PlaintextEncodings encoding, const std::vector<int64_t>& value, size_t depth,
                                uint32_t level) const;
    

    本函数依据编码方式 encoding,将整数向量 value 系数打包或者槽打包,乘法深度是 depth,水平是 level

  • Plaintext MakeStringPlaintext(const std::string& str) const;
    Plaintext MakeCoefPackedPlaintext(const std::vector<int64_t>& value, size_t noiseScaleDeg = 1,
                                          uint32_t level = 0) const;
    Plaintext MakePackedPlaintext(const std::vector<int64_t>& value, size_t noiseScaleDeg = 1,
                                      uint32_t level = 0) const;
    

    BGV/BFV 的三种打包方式:字符串、系数打包、槽打包

  • Plaintext MakeCKKSPackedPlaintext(const std::vector<std::complex<double>>& value, size_t scaleDeg = 1,
                                          uint32_t level = 0, const std::shared_ptr<ParmType> params = nullptr,
                                          usint slots = 0) const;
    

    CKKS 的打包方式,将复数向量 value 槽打包,水平是 level

  • static Plaintext GetPlaintextForDecrypt(PlaintextEncodings pte, std::shared_ptr<ParmType> evp, EncodingParams ep);
    

    构造一个用于解密运算的明文

  • static std::map<std::string, std::vector<EvalKey<Element>>>& evalMultKeyMap();
    static std::map<std::string, std::shared_ptr<std::map<usint, EvalKey<Element>>>>& evalSumKeyMap();
    static std::map<std::string, std::shared_ptr<std::map<usint, EvalKey<Element>>>>& evalAutomorphismKeyMap();
    

    返回上下文中存储的 Eval-Keys 字典,分别对应:乘法、加法、自同构

  • TypeCheckMismatchedCheckKeyCheckCiphertext,检查明文、密文、密钥、上下文是否匹配

  • GetPrivateKeySetPrivateKey,生成私钥

  • SerializeEvalMultKeyDeserializeEvalMultKeyClearEvalMultKeys,将 Eval-keys 序列化

  • GetKeyGenLevelGetCyclotomicOrderGetRingDimensionGetModulusGetRootOfUnity,获取使用的参数

  • KeyGenSparseKeyGen,生成公私钥

  • Ciphertext<Element> Encrypt(const Plaintext& plaintext, const PublicKey<Element> publicKey) const;
    Ciphertext<Element> Encrypt(const Plaintext& plaintext, const PrivateKey<Element> privateKey) const;
    

    公钥加密,私钥加密

  • DecryptResult Decrypt(ConstCiphertext<Element> ciphertext, const PrivateKey<Element> privateKey,
                              Plaintext* plaintext);
    

    解密运算

  • EvalKey<Element> KeySwitchGen(const PrivateKey<Element> oldPrivateKey,
                                      const PrivateKey<Element> newPrivateKey) const;
    

    生成 KS 密钥

  • Ciphertext<Element> KeySwitch(ConstCiphertext<Element> ciphertext, const EvalKey<Element> evalKey) const;
    void KeySwitchInPlace(Ciphertext<Element>& ciphertext, const EvalKey<Element> evalKey) const;
    

    执行 KS

  • EvalNegateEvalAddEvalAddMutableEvalAddInplaceEvalSub,执行同态加法/减法

  • void EvalMultKeyGen(const PrivateKey<Element> key);
    void EvalMultKeysGen(const PrivateKey<Element> key);
    

    生成 relin 密钥,前者只是 s 2 s^2 s2,后者是 s 2 , s 3 , ⋯ s^2,s^3,\cdots s2,s3,,密文乘法可以不立即 Relin,可以累积到 maxRelinSkDeg

  • EvalMultEvalMultMutableEvalMultInPlaceEvalSquare,执行同态乘法/平方

  • EvalMultNoRelinRelinearizeEvalMultAndRelinearize,张量积、重线性化

  • Ciphertext<Element> ModReduce(ConstCiphertext<Element> ciphertext) const;
    Ciphertext<Element> Rescale(ConstCiphertext<Element> ciphertext) const;
    Ciphertext<Element> LevelReduce(ConstCiphertext<Element> ciphertext, const EvalKey<Element> evalKey,
                                        size_t levels = 1) const;
    

    模切换(BGV/CKKS)、重缩放(CKKS),丢弃不需要的 RNS limbs

  • ComposedEvalMult,依次执行:张量积、重线性化、模切换/重缩放

  • std::shared_ptr<std::map<usint, EvalKey<Element>>> EvalAutomorphismKeyGen(
            const PrivateKey<Element> privateKey, const std::vector<usint>& indexList) const;
    

    生成 Galois 密钥

  • EvalAutomorphismFindAutomorphismIndexEvalRotate,执行 Galois 自同构

  • void EvalAtIndexKeyGen(const PrivateKey<Element> privateKey, const std::vector<int32_t>& indexList,
                               const PublicKey<Element> publicKey = nullptr);
    Ciphertext<Element> EvalAtIndex(ConstCiphertext<Element> ciphertext, int32_t index) const;
    

    执行槽旋转,正的 index 表示左移,负的 index 表示右移

  • std::shared_ptr<std::vector<Element>> EvalFastRotationPrecompute(ConstCiphertext<Element> ciphertext) const;
    Ciphertext<Element> EvalFastRotation(ConstCiphertext<Element> ciphertext, const usint index, const usint m,
                                             const std::shared_ptr<std::vector<Element>> digits) const;
    

    实现 [CH18] 中的 Hoisted automorphisms,用于同一个 ctxt 执行不同 index 自同构。前者计算数字分解步骤(它和 index 无关),后者执行 Galois 自同构步骤(使用 Pre 的分解结果)

  • Ciphertext<Element> KeySwitchExt(ConstCiphertext<Element> ciphertext, bool addFirst) const;
    Ciphertext<Element> KeySwitchDown(ConstCiphertext<Element> ciphertext) const;
    Ciphertext<Element> EvalFastRotationExt(ConstCiphertext<Element> ciphertext, usint index,
                                                const std::shared_ptr<std::vector<Element>> digits, bool addFirst) const;
    

    Hybrid-KS 模式下,前者把密文从 Q Q Q 扩展到 P Q PQ PQ,后者把密文从 P Q PQ PQ 缩放回 Q Q Q,而 EvalFastRotationExt 则是在 P Q PQ PQ 上执行的

  • Ciphertext<Element> Compress(ConstCiphertext<Element> ciphertext, uint32_t towersLeft = 1) const;
    

    把密文压缩到保证解密正确的最小模数上,BFV 也支持

  • Ciphertext<Element> EvalAddMany(const std::vector<Ciphertext<Element>>& ciphertextVec) const;
    Ciphertext<Element> EvalMultMany(const std::vector<Ciphertext<Element>>& ciphertextVec) const;
    

    二叉树方式,加法、乘法

  • EvalLinearWSumEvalLinearWSumMutable线性方式,带权重的加法,仅 CKKS 支持

  • virtual Ciphertext<Element> EvalPoly(ConstCiphertext<Element> ciphertext,
                                             const std::vector<double>& coefficients) const;
    Ciphertext<Element> EvalPolyLinear(ConstCiphertext<Element> ciphertext,
                                           const std::vector<double>& coefficients) const;
    Ciphertext<Element> EvalPolyPS(ConstCiphertext<Element> ciphertext, const std::vector<double>& coefficients) const;
    

    多项式求值,对于次数 ≥ 5 \ge 5 5 的多项式使用 [PS73] 的算法 C,对于次数 < 10 <10 <10 的多项式使用线性方式计算,仅 CKKS 支持,被用于 CKKS 自举

  • Ciphertext<Element> EvalChebyshevSeries(ConstCiphertext<Element> ciphertext,
                                                const std::vector<double>& coefficients, double a, double b) const;
    Ciphertext<Element> EvalChebyshevSeriesLinear(ConstCiphertext<Element> ciphertext,
                                                      const std::vector<double>& coefficients, double a, double b) const;
    Ciphertext<Element> EvalChebyshevSeriesPS(ConstCiphertext<Element> ciphertext,
                                                  const std::vector<double>& coefficients, double a, double b) const;         
    

    计算 Chebyshev polynomial interpolation(输入的系数关于 Chebyshev expansion)

  • Ciphertext<Element> EvalChebyshevFunction(std::function<double(double)> func, ConstCiphertext<Element> ciphertext,
                                                  double a, double b, uint32_t degree) const;
    Ciphertext<Element> EvalSin(ConstCiphertext<Element> ciphertext, double a, double b, uint32_t degree) const;
    Ciphertext<Element> EvalCos(ConstCiphertext<Element> ciphertext, double a, double b, uint32_t degree) const;
    Ciphertext<Element> EvalLogistic(ConstCiphertext<Element> ciphertext, double a, double b, uint32_t degree) const;
    Ciphertext<Element> EvalDivide(ConstCiphertext<Element> ciphertext, double a, double b, uint32_t degree) const;
    

    利用 Chebyshev approximation,非算术的连续函数 sin ⁡ x , cos ⁡ x , log ⁡ x , 1 / x \sin x,\cos x,\log x,1/x sinx,cosx,logx,1/x

  • EvalSumKeyGenEvalSumRowsKeyGenEvalSumColsKeyGen,用于槽打包的加法(旋转二的幂次)

  • EvalSumEvalSumRowsEvalSumColsEvalInnerProduct,分别是:整个矩阵、矩阵的各个行向量内的、各个行向量内的、两个向量的内积

  • EvalMerge,将多个密文的 slot- 0 0 0 打包在一起

  • EvalKey<Element> ReKeyGen(const PrivateKey<Element> oldPrivateKey, const PublicKey<Element> newPublicKey) const;
    

    生成 Proxy Re-Encryption 的密钥(是自举么?应该不是)

  • KeyPair<Element> MultipartyKeyGen(const std::vector<PrivateKey<Element>>& privateKeyVec);
    

    生成 ThFHE 的公私钥

  • std::vector<Ciphertext<Element>> MultipartyDecryptLead(const std::vector<Ciphertext<Element>>& ciphertextVec,
                                                               const PrivateKey<Element> privateKey) const;
    std::vector<Ciphertext<Element>> MultipartyDecryptMain(const std::vector<Ciphertext<Element>>& ciphertextVec,
                                                               const PrivateKey<Element> privateKey) const;
    DecryptResult MultipartyDecryptFusion(const std::vector<Ciphertext<Element>>& partialCiphertextVec,
                                              Plaintext* plaintext) const;
    

    leader 的部分解密、其他参与者的部分解密、leader 将它们组合

  • MultiKeySwitchGenMultiEvalAutomorphismKeyGenMultiEvalAtIndexKeyGenMultiEvalSumKeyGen,多方场景下的 Eval-Keys 生成

  • std::unordered_map<uint32_t, Element> ShareKeys(const PrivateKey<Element>& sk, usint N, usint threshold,
                                                        usint index, const std::string& shareType) const;
    void RecoverSharedKey(PrivateKey<Element>& sk, std::unordered_map<uint32_t, Element>& sk_shares, usint N,
                              usint threshold, const std::string& shareType) const;
    

    私钥的 LSSS

  • void EvalBootstrapSetup(std::vector<uint32_t> levelBudget = {5, 4}, std::vector<uint32_t> dim1 = {0, 0},
                                uint32_t slots = 0, uint32_t correctionFactor = 0);
    void EvalBootstrapKeyGen(const PrivateKey<Element> privateKey, uint32_t slots);
    Ciphertext<Element> EvalBootstrap(ConstCiphertext<Element> ciphertext, uint32_t numIterations = 1,
                                          uint32_t precision = 0) const;
    

    仅支持 CKKS 自举(迭代的 Meta-BTS),KeyGen 生成 BSGS 需要的 KSK,使用 FFT-like 或者 Linear 方法实现 StC 和 CtS

  • std::pair<BinFHEContext, LWEPrivateKey> EvalCKKStoFHEWSetup(SecurityLevel sl      = HEStd_128_classic,
                                                                    BINFHE_PARAMSET slBin = STD128, bool arbFunc = false,
                                                                    uint32_t logQ = 25, bool dynamic = false,
                                                                    uint32_t numSlotsCKKS = 0, uint32_t logQswitch = 27);
    void EvalFHEWtoCKKSSetup(const BinFHEContext& ccLWE, uint32_t numSlotsCKKS = 0, uint32_t logQ = 25);
    std::vector<std::shared_ptr<LWECiphertextImpl>> EvalCKKStoFHEW(ConstCiphertext<Element> ciphertext,
                                                                       uint32_t numCtxts = 0);
    Ciphertext<Element> EvalFHEWtoCKKS(std::vector<std::shared_ptr<LWECiphertextImpl>>& LWECiphertexts,
                                           uint32_t numCtxts = 0, uint32_t numSlots = 0, uint32_t p = 4, double pmin = 0.0,
                                           double pmax = 2.0) const;
    

    Pegasus 框架,FHEW 和 CKKS 之间的密文切换

  • EvalCompareSchemeSwitchingEvalMinSchemeSwitchingEvalMinSchemeSwitchingAlt,利用 FHEW 计算 CKKS 的符号函数

共享指针:using CryptoContext = std::shared_ptr<CryptoContextImpl<Element>>;

crypto-context-factory

管理当前已生成的所有上下文。

crypto-object

用于各个密码对象的上下文引用。

class CryptoObject

  • CryptoContext<Element> context; 所关联的上下文(共享指针)
  • std::string keyTag; 所关联的密钥标签(共享指针)

constants

定义了许多常数,

  • enum PKESchemeFeature {
        PKE          = 0x01,
        KEYSWITCH    = 0x02,
        PRE          = 0x04,
        LEVELEDSHE   = 0x08,
        ADVANCEDSHE  = 0x10,
        MULTIPARTY   = 0x20,
        FHE          = 0x40,
        SCHEMESWITCH = 0x80,
    };
    

    所支持的模式:对称/公钥、密钥切换、Proxy Re-Encryption、Leveled 版本(基本的乘法/加法)、Advanced 版本(Add-Many,Mult-Many,Eval-Poly 等等,只有 CKKS 支持)、自举(只有 CKKS 支持)、门限版本、方案切换(Pegasus,只有 CKKS 支持)

  • enum ScalingTechnique {
        FIXEDMANUAL = 0,
        FIXEDAUTO,
        FLEXIBLEAUTO,
        FLEXIBLEAUTOEXT,
        NORESCALE,
        INVALID_RS_TECHNIQUE,  // TODO (dsuponit): make this the first value
    };
    

    BGV 的模切换模式:[BGV12] 的手动模切换,[BGV12] 的乘法之后自动模切换,[GHS12] 的乘法之前自动模切换(除了第一次),[GHS12] 的乘法之前自动模切换(包含第一次)。其中 FIXED 速度快,而 FLEXIBLE 模数小。

    CKKS 的重缩放模式:[CHKKS18] 的手动重缩放,[CHKKS18] 的乘法之前自动重缩放(除了第一次),[KPP22] 的乘法之前自动重缩放(除了第一次),[KPP22] 的乘法之前自动重缩放(包含第一次)。其中 FIXED 速度快,而 FLEXIBLE 精度高。

  • enum MultiplicationTechnique {
        BEHZ = 0,
        HPS,
        HPSPOVERQ,
        HPSPOVERQLEVELED,
    };
    

    BFV 的同态乘法模式:[BEHZ16] 的整数指令 FastBaseExt,[HPS19] 的浮点指令 FastBaseExt,[KPZ21] 的大模数下加密,[KPZ21] 的隐式模切换。所有四种的加密都采用在线舍入,噪声比原始 B/FV 更小。其中 BEHZ 较慢,HPSPOVERQLEVELED 最快。

  • enum KeySwitchTechnique {
        INVALID_KS_TECH = 0,
        BV,
        HYBRID,
    };
    

    密钥切换的模式:[BV11] 的数字分解,[GHS12] 的混合版本

  • enum PlaintextEncodings {
        INVALID_ENCODING = 0,
        COEF_PACKED_ENCODING,
        PACKED_ENCODING,
        STRING_ENCODING,
        CKKS_PACKED_ENCODING,
    };
    

    明文编码的模式:BGV/BFV 的系数打包、槽打包、把 7-bit ASCII 字符串打包到多项式系数(必须明文模数 256 256 256),CKKS 的复数打包

  • enum MultipartyMode {
        INVALID_MULTIPARTY_MODE = 0,
        FIXED_NOISE_MULTIPARTY,
        NOISE_FLOODING_MULTIPARTY,
    };
    

    多方安全计算的模式:固定噪声、噪声洪泛

ciphertext

定义了密文类型(环元素的向量)。

class CiphertextImpl : public CryptoObject<Element>,密文的实现

  • explicit CiphertextImpl(CryptoContext<Element> cc, const std::string& id = "",
                                PlaintextEncodings encType = INVALID_ENCODING);
    CiphertextImpl(const CiphertextImpl<Element>& ciphertext);	//copy
    CiphertextImpl(CiphertextImpl<Element>&& ciphertext);		//move
    

    构造器

  • void SetElements(const std::vector<Element>& elements);
    std::vector<Element>& GetElements();
    

    对包含的环元素的读写

  • GetNoiseScaleDeg GetScalingFactorGetScalingFactorIntGetLevelGetSlots,噪声的缩放、消息的缩放、所在的水平、明文槽数量

  • friend std::ostream& operator<<(std::ostream& out, const CiphertextImpl<Element>& c);
    

    打印

一些类外函数:

  • Ciphertext<Element> operator+(const Ciphertext<Element>& a, const Ciphertext<Element>& b);
    const Ciphertext<Element>& operator+=(Ciphertext<Element>& a, const Ciphertext<Element>& b);
    

    密文加法( R q [ s ] R_q[s] Rq[s] 上的加法)

  • Ciphertext<Element> operator*(const Ciphertext<Element>& a, const Ciphertext<Element>& b);
    const Ciphertext<Element>& operator*=(Ciphertext<Element>& a, const Ciphertext<Element>& b);
    

    密文乘法( R q [ s ] R_q[s] Rq[s] 上的乘法),不做密钥切换,BGV 不做模切换,BFV 自动缩放

encoding

plaintext

定义了明文类型(单个环元素)。

class PlaintextImpl,明文的实现,

  • enum PtxtPolyType { IsPoly, IsDCRTPoly, IsNativePoly };
    bool isEncoded;
    mutable Poly encodedVector;
    mutable NativePoly encodedNativeVector;
    mutable DCRTPoly encodedVectorDCRT;
    

    多项式的三种数据存储格式:大整数(多精度表示)、机器字(64/128-bit)、DoubleCRT(RNS + NTT)

  • PlaintextImpl(const std::shared_ptr<Poly::Params>& vp, EncodingParams ep, SCHEME schemeTag = SCHEME::INVALID_SCHEME,
                      bool isEncoded = false);
    PlaintextImpl(const std::shared_ptr<NativePoly::Params>& vp, EncodingParams ep, SCHEME schemeTag = SCHEME::INVALID_SCHEME,
                      bool isEncoded = false);
    PlaintextImpl(const std::shared_ptr<DCRTPoly::Params>& vp, EncodingParams ep, SCHEME schemeTag = SCHEME::INVALID_SCHEME,
                      bool isEncoded = false);
    

    构造器

  • GetScalingFactor(CKKS),GetScalingFactorInt(BGV),消息的缩放因子

  • Encode, Decode, IsEncoded,将内部存储的多项式编码/解码

  • LowBound, HighBound,返回系数的区间 [ ⌊ − p / 2 ⌋ , ⌊ p / 2 ⌋ ] \big[\lfloor-p/2\rfloor, \lfloor p/2\rfloor\big] [p/2,p/2]

  • GetElementRingDimension, GetElementModulus, GetLength,维度、模数、比特长度

  • GetNoiseScaleDeg, GetLevel, GetSlots,噪声的缩放因子、所在的水平、明文槽数量

  • GetLogError, GetLogPrecision,噪声大小、计算精度,用于 CKKS 的带噪明文

  • virtual const std::string& GetStringValue() const;
    virtual const std::vector<int64_t>& GetCoefPackedValue() const;
    virtual const std::vector<int64_t>& GetPackedValue() const;
    virtual const std::vector<std::complex<double>>& GetCKKSPackedValue() const;
    virtual const std::vector<double> GetRealPackedValue() const;
    

    从明文中获得所编码的消息:字符串、系数打包、槽打包、复数打包、实数打包

  • friend std::ostream& operator<<(std::ostream& out, const PlaintextImpl& item);
    

    打印

plaintext-factory

根据数据,构造明文。

class PlaintextFactory

  • static Plaintext MakePlaintext(const std::vector<int64_t>& value, PlaintextEncodings encoding,
                                       std::shared_ptr<T> vp, EncodingParams ep, SCHEME schemeID = SCHEME::INVALID_SCHEME,
                                       size_t noiseScaleDeg = 1, uint32_t level = 0, NativeInteger scalingFactor = 1);
                                       static Plaintext MakePlaintext(const std::string& value, PlaintextEncodings encoding, std::shared_ptr<T> vp,
                                       EncodingParams ep, SCHEME schemeID = SCHEME::INVALID_SCHEME,
                                       size_t noiseScaleDeg = 1, uint32_t level = 0, NativeInteger scalingFactor = 1);
    

    将数据 value 根据 encoding 编码为明文

coef-encoding

定义了 BGV/BFV 系数打包的方法。

class CoefPackedEncoding : public PlaintextImpl,系数打包

  • std::vector<int64_t> value; 存储所编码的消息(整数)

  • 继承自 PlaintextImpl 的三种多项式,存储编码值

  • CoefPackedEncoding(std::shared_ptr<T> vp, EncodingParams ep, const std::vector<int64_t>& coeffs,
                           SCHEME schemeId = SCHEME::INVALID_SCHEME);
    

    构造器,只将 coeffs 存储到 value 中,不会自动编码

  • GetCoefPackedValue, SetIntVectorValue,对 value 的读写

  • Encode, Decode,编码/解码

packed-encoding

定义了 BGV/BFV 槽打包的方法。

class PackedEncoding : public PlaintextImpl,槽打包

  • std::vector<int64_t> value; 存储所编码的消息(素域元素,不支持复杂的明文槽

  • 继承自 PlaintextImpl 的三种多项式,存储编码值

  • PackedEncoding(std::shared_ptr<T> vp, EncodingParams ep, const std::vector<int64_t>& coeffs)
    

    构造器,不会自动编码

  • GetPackedValue, SetIntVectorValue,对 value 的读写

  • Encode, Decode,编码/解码

  • Pack, Unpack,私有属性,slot values 和 aggregated plaintext 之间的转换

ckks-encoding

定义了 CKKS 槽打包的方法。

class CKKSPackedEncoding : public PlaintextImpl,槽打包

  • std::vector<std::complex<double>> value; 存储所编码的消息(复数)

  • 继承自 PlaintextImpl 的三种多项式,存储编码值

  • CKKSPackedEncoding(std::shared_ptr<T> vp, EncodingParams ep, const std::vector<std::complex<double>>& coeffs,
                           size_t noiseScaleDeg, uint32_t level, double scFact, size_t slots);
    

    构造器,其中 slots 需要是二的幂次(子环),noiseScaleDeg 是消息的缩放因子

  • GetCKKSPackedValue, GetRealPackedValue,对 value 的读取,后者只读取实部

  • Encode, Decode,编码/解码

  • GetLogError, GetLogPrecision,估计标准差、估计精度

string-encoding

定义了字符串的打包方法。

class StringEncoding : public PlaintextImpl

  • std::string ptx; 存储字符串

  • StringEncoding(std::shared_ptr<T> vp, EncodingParams ep, const std::string& str);
    

    构造器,把字符串复制进来,only supports strings of 7-bit ASCII characters

  • Encode, Decode,编码/解码

key

class Key : public CryptoObject<Element>, public Serializable,所有密钥的高级接口,简单地继承了 CryptoObject 中的共享指针(上下文、标签)

priv-key

class PrivateKeyImpl : public Key<Element>,定义了私钥

  • Element m_sk; 存储私钥(单个环元素,using Element = DCRTPoly;

  • explicit PrivateKeyImpl(CryptoContext<Element> cc = 0);
    

    构造器

  • GetPrivateElement, SetPrivateElement,私钥元素的读写

pub-key

class PublicKeyImpl : public Key<Element>,定义了公钥

  • std::vector<Element> m_h; 存储公钥(环元素的向量,零的密文)

  • explicit PublicKeyImpl(CryptoContext<Element> cc = 0, const std::string& id = "");
    

    构造器

  • GetPublicElements, SetPublicElements, SetPublicElementAtIndex,公钥元素的读写

eval-key

class EvalKeyImpl : public Key<Element>,定义了运算密钥(重线性化、自同构、自举)的虚拟接口,不含数据成员

  • explicit EvalKeyImpl(CryptoContext<Element> cc = 0) : Key<Element>(cc);
    

    构造器

  • virtual void SetAVector(const std::vector<Element>& a);
    virtual void SetBVector(const std::vector<Element>& b);
    

    分别设置向量 A 和向量B,加密了密钥相关消息的密文的第一/第二分量组成的向量

relin-key

class EvalKeyRelinImpl : public EvalKeyImpl<Element>,重线性化密钥,

  • std::vector<std::vector<Element>> m_rKey;	// private member to store vector of vector of Element
    std::vector<DCRTPoly> m_dcrtKeys;	// Used for hybrid key switching
    

    前者是 KSK(密文的向量),加密了私钥幂次的 powers-of-base,形如 R L W E ( s i ⋅ g j ⋅ P ) RLWE(s^i\cdot g_j \cdot P) RLWE(sigjP),其中 P P P 是特殊模数, g ⃗ \vec g g 是 Gadget 向量(PolyDCRTPoly使用的都是 Digit-Decompose 而非 RNS-Decompose

    后者是干嘛的?在 keyswitch-hybrid.cpp 中并没有用到。

  • explicit EvalKeyRelinImpl(CryptoContext<Element> cc = 0);
    

    构造器

  • virtual void SetAVector(const std::vector<Element>& a) {
    	m_rKey.insert(m_rKey.begin() + 0, a);
    }
    virtual void SetBVector(const std::vector<Element>& b) {
    	m_rKey.insert(m_rKey.begin() + 1, b);
    }
    

    设置 m_rKey[0] = a 以及 m_rKey[1] = b,这里的 a, b 分别是 KSK 的第一/第二分量组成的环元素向量

keyswitch

class KeySwitchBase,基类,仅定义了一些虚拟接口,用于派生 BV-type 或者 Hybrid-type

bv

class KeySwitchBV : public KeySwitchRNS,实现了 BV-type KS 过程

  • EvalKey<DCRTPoly> KeySwitchGenInternal(const PrivateKey<DCRTPoly> oldPrivateKey,
                                               const PrivateKey<DCRTPoly> newPrivateKey) const override;
    

    生成 KSK,这里 old-keynew-key 都是 DCRTPoly 格式的单个环元素,混合采用 RNS-Decompose 以及 Digit-Decompose,形如 R L W E s n e w ( [ [ s o l d ] q i ⋅ B j ] Q ) RLWE_{s_{new}}\Big(\big[[s_{old}]_{q_i} \cdot B^j\big]_{Q}\Big) RLWEsnew([[sold]qiBj]Q)

  • void KeySwitchInPlace(Ciphertext<DCRTPoly>& ciphertext, const EvalKey<DCRTPoly> evalKey) const override;
    

    执行 KS 过程,只处理 2 次多项式(密钥切换)或者 3 次多项式(重线性化)

  • std::shared_ptr<std::vector<DCRTPoly>> KeySwitchCore(const DCRTPoly& a,
                                                             const EvalKey<DCRTPoly> evalKey) const override;
    

    核心运算:外积(Gadget 分解 + 内积 = 强线性同态),可以用这个自己搭建更复杂的密钥切换

  • std::shared_ptr<std::vector<DCRTPoly>> EvalKeySwitchPrecomputeCore(
            const DCRTPoly& c, std::shared_ptr<CryptoParametersBase<DCRTPoly>> cryptoParamsBase) const override;
    std::shared_ptr<std::vector<DCRTPoly>> EvalFastKeySwitchCore(
            const std::shared_ptr<std::vector<DCRTPoly>> digits, const EvalKey<DCRTPoly> evalKey,
            const std::shared_ptr<ParmType> paramsQl) const override;
    

    前者将单个环元素 c 预先分解(RNS-Decompose + Digit-Decompose),形如 D C R T ( [ ( [ c ] q i / B j )   m o d   B ] Q ) DCRT\Big(\big[([c]_{q_i}/B^j) \bmod B\big]_{Q}\Big) DCRT([([c]qi/Bj)modB]Q),后者将它和(多个不同的)KSK 做内积。

hybrid

class KeySwitchHYBRID : public KeySwitchRNS 实现了 Hybrid-type KS 过程

  • EvalKey<DCRTPoly> KeySwitchGenInternal(const PrivateKey<DCRTPoly> oldPrivateKey,
                                               const PrivateKey<DCRTPoly> newPrivateKey) const override;
    

    生成 KSK,本来 new-key 的模数是 Q Q Q,先扩展到 P Q PQ PQ 上,然后加密 old-key 的缩放的 Powers-of-base(只使用 RNS-Decompose),形如 R L W E s n e w ( [ [ P ⋅ s o l d ] Q i ] P Q ) RLWE_{s_{new}}\Big(\big[[P \cdot s_{old}]_{Q_i}\big]_{PQ}\Big) RLWEsnew([[Psold]Qi]PQ),其中 Q i = ∏ j ∈ I i q j Q_i = \prod_{j \in I_i} q_j Qi=jIiqj 是模数 Q Q Q 的某个小区块(称为 part)

  • void KeySwitchInPlace(Ciphertext<DCRTPoly>& ciphertext, const EvalKey<DCRTPoly> evalKey) const override;
    

    执行 KS 过程,ciphertext 被视为 R Q R_Q RQ 中的常数,也只处理 2 次或者 3 次多项式

  • Ciphertext<DCRTPoly> KeySwitchExt(ConstCiphertext<DCRTPoly> ciphertext, bool addFirst) const override;
    Ciphertext<DCRTPoly> KeySwitchDown(ConstCiphertext<DCRTPoly> ciphertext) const override;
    

    KeySwitchExt 把环元素 [ c ] Q [c]_Q [c]Q 扩展到 [ P c ] P Q = [ P c ] Q ∥ [ 0 ] P [Pc]_{PQ}=[Pc]_Q\|[0]_P [Pc]PQ=[Pc]Q[0]P,这里的 ciphertext任意长的向量addFirst 控制是否处理 c 0 c_0 c0 否则置为 [ 0 ] P Q [0]_{PQ} [0]PQ

    KeySwitchDown 把环元素 [ c ] P Q [c]_{PQ} [c]PQ 切换回 [ c ] Q [c]_Q [c]Q,它要求 ciphertext线性多项式(模数 P Q PQ PQ 上密文和 KSK 的内积结果),两个分量都做了 ApproxModDown

    • 对于 BGV,令 t t t 是明文模数,先计算 r = [ t − 1 ⋅ c ] P r=[t^{-1} \cdot c]_P r=[t1c]P,然后扩展到 [ r ] Q [r]_Q [r]Q 并计算 δ = [ t ⋅ r ] Q \delta=[t \cdot r]_Q δ=[tr]Q(满足 t ⋅ r ≡ 0   m o d   t t \cdot r \equiv 0 \bmod t tr0modt 以及 t ⋅ r ≡ c   m o d   P t \cdot r \equiv c \bmod P trcmodP),最后计算出 c ′ = [ P − 1 ⋅ ( c − δ ) ] Q c'=[P^{-1} \cdot (c-\delta)]_Q c=[P1(cδ)]Q,它满足 c ′ ≈ c / P c' \approx c/P cc/P 以及 [ [ c ′ ] Q ] t = [ P − 1 ⋅ [ c ] P Q ] t [[c']_Q]_t = [P^{-1}\cdot[c]_{PQ}]_t [[c]Q]t=[P1[c]PQ]t扭曲的消息
    • 对于 BFV,直接把 r = [ c ] P r=[c]_P r=[c]P 扩展到 [ r ] Q [r]_Q [r]Q,计算出 c ′ = [ P − 1 ⋅ ( c − r ) ] Q c'=[P^{-1}\cdot(c-r)]_Q c=[P1(cr)]Q,它满足 c ′ ≈ c / P c' \approx c/P cc/P 以及 ⌊ t c / P Q ⌉ = ⌊ t c ′ / Q ⌉ \lfloor tc/PQ\rceil = \lfloor tc'/Q\rceil tc/PQ=tc/Q原始的消息
  • std::shared_ptr<std::vector<DCRTPoly>> KeySwitchCore(const DCRTPoly& a,
                                                             const EvalKey<DCRTPoly> evalKey) const override;
    

    外积运算,Gadget 分解 + 内积

  • std::shared_ptr<std::vector<DCRTPoly>> EvalKeySwitchPrecomputeCore(
            const DCRTPoly& c, std::shared_ptr<CryptoParametersBase<DCRTPoly>> cryptoParamsBase) const override;
    std::shared_ptr<std::vector<DCRTPoly>> EvalFastKeySwitchCore(
            const std::shared_ptr<std::vector<DCRTPoly>> digits, const EvalKey<DCRTPoly> evalKey,
            const std::shared_ptr<ParmType> paramsQl) const override;
    std::shared_ptr<std::vector<DCRTPoly>> EvalFastKeySwitchCoreExt(
            const std::shared_ptr<std::vector<DCRTPoly>> digits, const EvalKey<DCRTPoly> evalKey,
            const std::shared_ptr<ParmType> paramsQl) const override;
    

    EvalKeySwitchPrecomputeCore 把单个环元素 [ c ] Q [c]_Q [c]Q 预先分解和提升(RNS-Decompose + ModUp),形如 D C R T ( [ [ c ] Q i ] P Q ) DCRT\Big(\big[[c]_{Q_i}\big]_{PQ}\Big) DCRT([[c]Qi]PQ)

    EvalFastKeySwitchCore 首先在 P Q PQ PQ 上做内积(和多个不同的 KSK 的线性同态),得到线性的密文,然后把两个分量模切换到 Q Q Q

    EvalFastKeySwitchCoreExt 作为 EvalFastKeySwitchCore 的子程序,在模数 P Q PQ PQ 上将 digitsevalKey 做线性同态

scheme-base

scheme

class SchemeBase,定义了 PKE 的定义,

  • void Enable(uint32_t mask);
    virtual void Enable(PKESchemeFeature feature);
    

    根据 mask 或者 feature,配置 PKE 支持的功能

  • ParamsGenBGVRNS, ParamsGenBFVRNS, ParamsGenCKKSRNS,三种方案的参数生成

  • KeyGen, Encrypt, EncryptZeroCore, Decrypt, DecryptCore,加解密算法

  • KeySwitchGen, KeySwitch, EvalKeySwitchPrecomputeCore, EvalFastKeySwitchCore,密钥切换

  • ReKeyGen, ReEncrypt代理重加密

  • EvalNegate, EvalAdd, EvalSub,同态加法

  • EvalMultKeyGen, EvalMult, EvalSquare, Relinearize,同态乘法(手动 重线性化,这很好)

  • EvalAutomorphismKeyGen, EvalAutomorphism, EvalFastRotationPrecompute, EvalFastRotation, EvalFastRotationExt,同态 Galois 自同构,Fast是 hoisting 优化的(预计算),Ext 是 hybrid-KS 优化的(模数 P Q PQ PQ 上)

  • ModReduce, LevelReduce, AdjustLevelsInPlace, AdjustLevelsAndDepthInPlace, Compress,模切换,调整密文水平,压缩密文

  • EvalAddMany, EvalMultMany, EvalLinearWSum, EvalPoly, EvalChebyshevSeries, EvalInnerProduct,高级算法

  • EvalSumKeyGen, EvalSumRowsKeyGen, EvalSumColsKeyGen, EvalSum, EvalSumRows, EvalSumCols, EvalMerge,同一个密文的不同明文槽之间的加法

  • AddRandomNoise,在密文中添加噪声

  • MultipartyKeyGen, MultipartyDecryptMain, MultipartyDecryptLead, MultipartyDecryptFusion分布式门限解密

  • EvalBootstrapSetup, EvalBootstrapKeyGen, EvalBootstrap,自举

  • EvalCKKStoFHEWSetup, EvalCKKStoFHEWKeyGen, EvalCKKStoFHEWPrecompute, EvalCKKStoFHEW,CKKS 和 FHEW 之间的方案切换

crypto-param

class CryptoParametersBase : public Serializable,参数的定义,用于派生 Scheme-RNS

param-gen

class ParameterGenerationBase,参数生成器的定义,用于派生 Scheme-RNS

pke

class PKEBase,加密/解密算法的定义,实现了一些函数模版:

  • KeyPair<Element> PKEBase<Element>::KeyGenInternal(CryptoContext<Element> cc, bool makeSparse);
    

    生成公私钥对,私钥的分布来自于上下文:GAUSSIAN、UNIFORM_TERNARY、SPARSE_TERNARY,参数 makeSparse 无用

  • Ciphertext<Element> PKEBase<Element>::Encrypt(Element plaintext, const PrivateKey<Element> privateKey) const;
    Ciphertext<Element> PKEBase<Element>::Encrypt(Element plaintext, const PublicKey<Element> publicKey) const;
    

    对称加密、公钥加密,形如 c 0 + c 1 s = E n c ( 0 ) + ( m , 0 ) ∈ R Q [ s ] c_0+c_1s = Enc(0) + (m,0) \in R_Q[s] c0+c1s=Enc(0)+(m,0)RQ[s],其中 m ∈ R m \in R mR打包和纠错编码之后的多项式

  • std::shared_ptr<std::vector<Element>> PKEBase<Element>::EncryptZeroCore(const PrivateKey<Element> privateKey,
                                                                            const std::shared_ptr<ParmType> params) const;
    std::shared_ptr<std::vector<Element>> PKEBase<Element>::EncryptZeroCore(const PublicKey<Element> publicKey,
                                                                            const std::shared_ptr<ParmType> params) const;
    

    零的加密(作为 Enc、KeyGen 等等的子程序)

  • Element PKEBase<Element>::DecryptCore(const std::vector<Element>& cv, const PrivateKey<Element> privateKey) const;
    

    密文视为一个环元素的向量(或者说 R Q [ s ] R_Q[s] RQ[s] 中的多项式),计算 ∑ i c i ⋅ s i ∈ R Q \sum_i c_i\cdot s^i \in R_Q icisiRQ不纠错

dec-result

struct DecryptResult,记录关于解密结果的一些信息

  • bool isValid;                   /**< whether the decryption was successful */
        usint messageLength;            /**< the length of the decrypted plaintext message */
        NativeInteger scalingFactorInt; /**< Scaling factor for BGV FlexibleAuto mode. */
    

    解密正确性、消息长度、BGV 明文的扭曲因子

  • explicit DecryptResult(size_t len, NativeInteger scf) : isValid(true), messageLength(len), scalingFactorInt(scf) {}
    

    构造器

leveled-she

class LeveledSHEBase,定义了 Leveled SHE 的接口,

  • EvalNegate, EvalAdd, EvalAddInPlace, EvalAddMutable,同态加法,其中 EvalAdd 要求两个密文的 Level 和 Depth 相同, inplace 把结果赋值到第一个输入,mutable 自动调整 Level 和 Depth(这里的 Level 指的是密文模数中素数的数量,Depth 指的是消息缩放因子)

  • EvalMultKeyGen, EvalMultKeysGen,前者生成 s 2 s^2 s2 的 relin-key,后者生成 s i s^i si 的 relin-keys,其中 i = 2 , 3 , ⋯   , maxRelinSkDeg i=2,3,\cdots,\text{maxRelinSkDeg} i=2,3,,maxRelinSkDeg

  • EvalMult, EvalSquare, MultByMonomial, MultByInteger,同态乘法,需要手动重线性化和模切换

  • EvalMultAndRelinearize, ComposedEvalMult,前者自动重线性化,后者自动重线性化和模切换

  • EvalAutomorphismKeyGen, EvalAutomorphism, EvalFastRotationPrecompute, EvalFastRotation,同态 Galois 自同构

  • ModReduce, LevelReduce,模切换、水平切换

  • Ciphertext<Element> LeveledSHEBase<Element>::MorphPlaintext(ConstPlaintext plaintext,
                                                                ConstCiphertext<Element> ciphertext) const;
    

    使用 ct 的参数,生成 pt 的无噪声密文(明文的编码放在密文的常数项)

  • Ciphertext<Element> LeveledSHEBase<Element>::EvalAddCore(ConstCiphertext<Element> ciphertext1,
                                                             ConstCiphertext<Element> ciphertext2) const;
    

    简单的多项式相加(要求输入密文具有匹配的参数)

  • Ciphertext<Element> LeveledSHEBase<Element>::EvalMultCore(ConstCiphertext<Element> ciphertext1,
                                                              ConstCiphertext<Element> ciphertext2) const;
    

    简单的多项式相乘(要求输入密文具有匹配的参数)

advanced-she

class AdvancedSHEBase,实现了一些高级算法

  • Ciphertext<Element> AdvancedSHEBase<Element>::EvalAddMany(const std::vector<Ciphertext<Element>>& ciphertextVec) const;
    

    二叉树式的加法,迭代算法:对于 n n n 个密文,申请长度 n − 1 n-1 n1 的数组,首先将相邻两个密文相加存放到前 n / 2 n/2 n/2 个位置,然后对这个数组从头扫一遍,相邻两个密文相加存放到下一个空位,最后输出数组的最后一个位置

  • Ciphertext<Element> AdvancedSHEBase<Element>::EvalMultMany(const std::vector<Ciphertext<Element>>& ciphertextVec,
                                                               const std::vector<EvalKey<Element>>& evalKeys) const;
    

    二叉树式的乘法,每次乘法之后都自动执行:重线性化、模切换

  • std::shared_ptr<std::map<usint, EvalKey<Element>>> AdvancedSHEBase<Element>::EvalSumKeyGen(
        const PrivateKey<Element> privateKey, const PublicKey<Element> publicKey) const;
    Ciphertext<Element> AdvancedSHEBase<Element>::EvalSum(ConstCiphertext<Element> ciphertext, usint batchSize,
                                                          const std::map<usint, EvalKey<Element>>& evalKeyMap) const;
    

    把长度 n ≤ N / 2 n \le N/2 nN/2 的向量打包在明文槽内,对应索引的生成元是 g ( m o d m ) g \pmod m g(modm),对于二的幂次 m = 2 N m=2N m=2N,可以选取 g = 3 g=3 g=3 o r d ( g ) = N / 2 ord(g)=N/2 ord(g)=N/2 以及 ⟨ − 1 , g ⟩ = Z m ∗ \langle-1,g\rangle = \mathbb Z_m^* 1,g=Zm。构造 g 2 i ( m o d m ) , i = 0 , 1 , ⋯   , l − 1 g^{2^i} \pmod m, i=0,1,\cdots,l-1 g2i(modm),i=0,1,,l1 对应的 Galois 自同构的 KSK,其中 l = ⌊ log ⁡ n ⌋ l = \lfloor \log n\rfloor l=logn(其他的都不需要)。如果 n > N / 2 n > N/2 n>N/2,那么还需要 − 1 -1 1 对应的 Galois 自同构的 KSK。然后迭代 l l l 轮的 “旋转 + 相加”,计算结果应该只在第一个明文槽内,其他明文槽不一定对。

  • Ciphertext<Element> AdvancedSHEBase<Element>::EvalMerge(const std::vector<Ciphertext<Element>>& ciphertextVec,
                                                            const std::map<usint, EvalKey<Element>>& evalKeyMap) const;
    

    输入多个密文,利用 Mask 把它们的第一个明文槽提取出来,合并到单个密文的不同明文槽上

fhe

class FHEBase,只定义了 FHE 的虚拟接口,没有给实现

  • 目前 OpenFHE 仅实现了 CKKS 的自举
  • 支持 CKKS 和 FHEW 的方案切换

pre

class PREBase,实现了代理重加密

  • EvalKey<Element> PREBase<Element>::ReKeyGen(const PrivateKey<Element> oldPrivateKey,
                                                const PublicKey<Element> newPublicKey) const;
    

    就是生成 KSK

  • Ciphertext<Element> PREBase<Element>::ReEncrypt(ConstCiphertext<Element> ciphertext, const EvalKey<Element> evalKey,
                                                    const PublicKey<Element> publicKey) const;
    

    首先使用 EncryptZeroCore 将输入的密文随机化(第二分量),然后再添加一个洪泛噪声(第一分量),最后执行 KS 过程(切换密钥)

multiparty

class MultipartyBase,实现了 ThFHE,为了各种 eval-key 的分布式生成,接口太繁琐。

scheme-rns

Scheme

class SchemeRNS : public SchemeBase<DCRTPoly>,根据模板派生

crypto-param

class CryptoParametersRNS : public CryptoParametersRLWE<DCRTPoly>,给出了 RNS-Scheme 参数集的实现

  • CryptoParametersRNS(std::shared_ptr<ParmType> params, const PlaintextModulus& plaintextModulus,
                            float distributionParameter, float assuranceMeasure, SecurityLevel securityLevel,
                            usint digitSize, SecretKeyDist secretKeyDist, int maxRelinSkDeg = 2,
                            KeySwitchTechnique ksTech = BV, ScalingTechnique scalTech = FIXEDMANUAL,
                            EncryptionTechnique encTech = STANDARD, MultiplicationTechnique multTech = HPS,
                            MultipartyMode multipartyMode                         = FIXED_NOISE_MULTIPARTY,
                            ExecutionMode executionMode                           = EXEC_EVALUATION,
                            DecryptionNoiseMode decryptionNoiseMode               = FIXED_NOISE_DECRYPT,
                            COMPRESSION_LEVEL mPIntBootCiphertextCompressionLevel = COMPRESSION_LEVEL::SLACK);
    

    构造器,设置各种参数

  • virtual void PrecomputeCRTTables(KeySwitchTechnique ksTech, ScalingTechnique scalTech, EncryptionTechnique encTech,
                                         MultiplicationTechnique multTech, uint32_t numPartQ, uint32_t auxBits,
                                         uint32_t extraBits);
    

    根据配置的参数,预计算用于解密、同态乘法、密钥切换的所有 CRT 表格

  • 包含大量的 protected 数据成员,记录了:密钥切换、模切换、数字分解、基扩展、BFV 缩放因子、CKKS 缩放因子、BGV 扭曲因子,等等。

param-gen

class ParameterGenerationRNS : public ParameterGenerationBase<DCRTPoly>,根据模板派生

pke

class PKERNS : public PKEBase<DCRTPoly>,给出了加解密算法的 RNS 实现

  • Encrypt,输入明文 m m m,输出 E n c ( 0 ) + ( m , 0 ) Enc(0)+(m,0) Enc(0)+(m,0),以 DCRTPoly 形式
  • Decrypt,输入密文 c t ct ct,输出 c t ( s ) ct(s) ct(s) 以及 DecryptResult 信息,以 PolyNativePoly 形式

leveled-she

class LeveledSHERNS : public LeveledSHEBase<DCRTPoly>,给出了 Leveled SHE 各种运算的 RNS 实现

  • 同态加法、同态乘法
  • 模切换、水平切换、密文压缩

multiparty

class MultipartyRNS : public MultipartyBase<DCRTPoly>,给出了 ThFHE 的 RNS 实现

bgv-rns

scheme

class SchemeBGVRNS : public SchemeRNS,派生

crypto-param

class CryptoParametersBGVRNS : public CryptoParametersRNS,实现了 PrecomputeCRTTables 函数

param-gen

class ParameterGenerationBGVRNS : public ParameterGenerationRNS,实现了 BGV 参数生成器

  • bool ParamsGenBGVRNS(std::shared_ptr<CryptoParametersBase<DCRTPoly>> cryptoParams, uint32_t evalAddCount,
                             uint32_t keySwitchCount, usint cyclOrder, usint numPrimes, usint firstModSize, usint dcrtBits,
                             uint32_t numPartQ, usint multihopQBound) const override;
    

    构造器,根据配置生成 BGV 参数

  • computeRingDimension, computeNoiseEstimates, getCyclicOrder, computeModuli, InitializeFloodingDgg,私有的函数

pke

class PKEBGVRNS : public PKERNS,实现了 Decrypt 函数,包含 LSD 解码

leveled-she

class LeveledSHEBGVRNS : public LeveledSHERNS,实现了以下函数

  • void ModReduceInternalInPlace(Ciphertext<DCRTPoly>& ciphertext, size_t levels) const override;
    

    模切换:对于每个环元素 [ c ] Q l [c]_{Q_l} [c]Ql 分别模切换到 [ c ] Q l ′ [c]_{Q_{l'}} [c]Ql,删除的个数是 l e v e l s = l − l ′ levels = l-l' levels=ll,使用 Approx-ModDown 依次删除 Q l / Q l ′ Q_l/Q_{l'} Ql/Ql 中的各个素数(缩放 + 舍入,相位缩小、明文扭曲

  • void LevelReduceInternalInPlace(Ciphertext<DCRTPoly>& ciphertext, size_t levels) const override;
    

    水平切换:直接丢弃模数链的最后 levels 个素数对应的 RNS 分量(简单取模,相位不变、明文不变

  • void AdjustLevelsAndDepthInPlace(Ciphertext<DCRTPoly>& ciphertext1,
                                         Ciphertext<DCRTPoly>& ciphertext2) const override;
    void AdjustLevelsAndDepthToOneInPlace(Ciphertext<DCRTPoly>& ciphertext1,
                                              Ciphertext<DCRTPoly>& ciphertext2) const override;
    

    调整 Level 和 Depth 使得两个密文相互匹配

advanced-she

class AdvancedSHEBGVRNS : public AdvancedSHERNS,派生

multiparty

class MultipartyBGVRNS : public MultipartyRNS,实现了 MultipartyDecryptFusion 函数

bfv-rns

scheme

class SchemeBFVRNS : public SchemeRNS,派生

crypto-param

class CryptoParametersBFVRNS : public CryptoParametersRNS,实现了 PrecomputeCRTTables 函数

param-gen

class ParameterGenerationBFVRNS : public ParameterGenerationRNS,实现了 BFV 的参数生成器

  • bool ParamsGenBFVRNS(std::shared_ptr<CryptoParametersBase<DCRTPoly>> cryptoParams, uint32_t evalAddCount,
                             uint32_t multiplicativeDepth, uint32_t keySwitchCount, size_t dcrBits, uint32_t n,
                             uint32_t numPartQ) const override;
    

    构造器,根据配置生成 BFV 参数

pke

class PKEBFVRNS : public PKERNS,实现了 KeyGenInternal, Encrypt, Decrypt 函数,包含 MSD 编码/解码

leveled-she

class LeveledSHEBFVRNS : public LeveledSHERNS,实现了以下函数

  • uint32_t FindLevelsToDrop(usint multiplicativeDepth, std::shared_ptr<CryptoParametersBase<DCRTPoly>> cryptoParams,
                              uint32_t dcrtBits, bool keySwitch = false);
    

    同态乘法中的隐式模切换

  • EvalMult, EvalSquare,实现了 Leveled BFV-Mult 算法

  • EvalAutomorphism, EvalFastRotationPrecompute, EvalFastRotation,实现 Galois 自同构

  • RelinearizeCore,上述自同构算法的子程序,也使用 FindLevelsToDrop 把密文缩放之后再和 KSK 内积

  • Compress,密文压缩,缩放到更小的模数上

advanced-she

class AdvancedSHEBFVRNS : public AdvancedSHERNS,派生

multiparty

class MultipartyBFVRNS : public MultipartyRNS,实现了 MultipartyKeyGenMultipartyDecryptFusion 函数

ckks-rns

utils

实现了一些零碎的小工具,用于 CKKS 自举。

scheme

class SchemeCKKSRNS : public SchemeRNS,派生

crypto-param

class CryptoParametersCKKSRNS : public CryptoParametersRNS,实现了 PrecomputeCRTTables 函数

param-gen

class ParameterGenerationCKKSRNS : public ParameterGenerationRNS,实现了 CKKS 的参数生成器

  • bool ParameterGenerationCKKSRNS::ParamsGenCKKSRNS(std::shared_ptr<CryptoParametersBase<DCRTPoly>> cryptoParams,
                                                      usint cyclOrder, usint numPrimes, usint scalingModSize,
                                                      usint firstModSize, uint32_t numPartQ,
                                                      COMPRESSION_LEVEL mPIntBootCiphertextCompressionLevel) const;
    

    构造器,根据配置生成 CKKS 参数

pke

class PKECKKSRNS : public PKERNS,实现了 Decrypt 函数,添加了洪泛噪声

leveled-she

class LeveledSHECKKSRNS : public LeveledSHERNS,实现了以下函数

  • EvalAdd, EvalSub, EvalMult, EvalMultCoreInPlace,同态操作

  • ModReduceInternalInPlace,模切换(缩放和舍入)

  • LevelReduceInternalInPlace,水平切换(删除一些 RNS 分量)

  • std::vector<DCRTPoly::Integer> LeveledSHECKKSRNS::GetElementForEvalAddOrSub(ConstCiphertext<DCRTPoly> ciphertext,
                                                                                double operand) const;
    

    把浮点数 operand 缩放为 RNS 整数,匹配 ciphertext 的加法需求

  • std::vector<DCRTPoly::Integer> LeveledSHECKKSRNS::GetElementForEvalMult(ConstCiphertext<DCRTPoly> ciphertext,
                                                                            double operand) const;
    

    把浮点数 operand 缩放为 RNS 整数,匹配 ciphertext 的乘法需求

  • EvalFastRotationExt,实现了 P Q PQ PQ 上的槽旋转

  • AdjustLevelsAndDepthInPlace,把两个密文的 Level 和 Depth 调整到一致

advaned-she

class AdvancedSHECKKSRNS : public AdvancedSHERNS,实现了高级算法

  • EvalLinearWSum,带权的加法
  • EvalPoly,多项式求值
  • EvalChebyshevSeries,切比雪夫插值多项式的求值

fhe

class CKKSBootstrapPrecom,用于自举的预计算

  • // the inner dimension in the baby-step giant-step strategy
    uint32_t m_dim1 = 0;
    
    // number of slots for which the bootstrapping is performed
    uint32_t m_slots = 0;
    
    // level budget for homomorphic encoding, number of layers to collapse in one level,
    // number of layers remaining to be collapsed in one level to have exactly the number
    // of levels specified in the level budget, the number of rotations in one level,
    // the baby step and giant step in the baby-step giant-step strategy, the number of
    // rotations in the remaining level, the baby step and giant step in the baby-step
    // giant-step strategy for the remaining level
    std::vector<int32_t> m_paramsEnc = std::vector<int32_t>(CKKS_BOOT_PARAMS::TOTAL_ELEMENTS, 0);
    
    // level budget for homomorphic decoding, number of layers to collapse in one level,
    // number of layers remaining to be collapsed in one level to have exactly the number
    // of levels specified in the level budget, the number of rotations in one level,
    // the baby step and giant step in the baby-step giant-step strategy, the number of
    // rotations in the remaining level, the baby step and giant step in the baby-step
    // giant-step strategy for the remaining level
    std::vector<int32_t> m_paramsDec = std::vector<int32_t>(CKKS_BOOT_PARAMS::TOTAL_ELEMENTS, 0);
    
    // Linear map U0; used in decoding
    std::vector<ConstPlaintext> m_U0Pre;
    
    // Conj(U0^T); used in encoding
    std::vector<ConstPlaintext> m_U0hatTPre;
    
    // coefficients corresponding to U0; used in decoding
    std::vector<std::vector<ConstPlaintext>> m_U0PreFFT;
    
    // coefficients corresponding to conj(U0^T); used in encoding
    std::vector<std::vector<ConstPlaintext>> m_U0hatTPreFFT;
    

    存储自举所需的各种参数

class FHECKKSRNS : public FHERNS,实现了 CKKS 自举

  • void EvalBootstrapSetup(const CryptoContextImpl<DCRTPoly>& cc, std::vector<uint32_t> levelBudget,
                                std::vector<uint32_t> dim1, uint32_t slots, uint32_t correctionFactor,
                                bool precompute) override;
    

    初始化

  • std::shared_ptr<std::map<usint, EvalKey<DCRTPoly>>> EvalBootstrapKeyGen(const PrivateKey<DCRTPoly> privateKey,
                                                                                uint32_t slots) override;
    

    生成自举密钥

  • void EvalBootstrapPrecompute(const CryptoContextImpl<DCRTPoly>& cc, uint32_t slots) override;
    

    自举的预计算

  • Ciphertext<DCRTPoly> EvalBootstrap(ConstCiphertext<DCRTPoly> ciphertext, uint32_t numIterations,
                                           uint32_t precision) const override;
    

    执行自举:ModRaise, PartialSum, CtS, Approx-ModReduce, StC。取模函数采用了切比雪夫插值的 sin ⁡ \sin sin 函数,支持 2 2 2 轮迭代的 Beta-BTS

  • std::vector<ConstPlaintext> EvalLinearTransformPrecompute(const CryptoContextImpl<DCRTPoly>& cc,
                                                                  const std::vector<std::vector<std::complex<double>>>& A,
                                                                  double scale = 1, uint32_t L = 0) const;
    

    线性变换的预计算

  • Ciphertext<DCRTPoly> EvalLinearTransform(const std::vector<ConstPlaintext>& A, ConstCiphertext<DCRTPoly> ct) const;
    

    执行线性变换,使用 BSGS 算法

  • std::vector<std::vector<ConstPlaintext>> EvalCoeffsToSlotsPrecompute(const CryptoContextImpl<DCRTPoly>& cc,
                                                                             const std::vector<std::complex<double>>& A,
                                                                             const std::vector<uint32_t>& rotGroup,
                                                                             bool flag_i, double scale = 1,
                                                                             uint32_t L = 0) const;
    std::vector<std::vector<ConstPlaintext>> EvalSlotsToCoeffsPrecompute(const CryptoContextImpl<DCRTPoly>& cc,
                                                                             const std::vector<std::complex<double>>& A,
                                                                             const std::vector<uint32_t>& rotGroup,
                                                                             bool flag_i, double scale = 1,
                                                                             uint32_t L = 0) const;
    

    CtS 和 StC 的预计算

  • Ciphertext<DCRTPoly> EvalCoeffsToSlots(const std::vector<std::vector<ConstPlaintext>>& A,
                                               ConstCiphertext<DCRTPoly> ctxt) const;
    Ciphertext<DCRTPoly> EvalSlotsToCoeffs(const std::vector<std::vector<ConstPlaintext>>& A,
                                               ConstCiphertext<DCRTPoly> ctxt) const;
    

    执行 CtS 和 StC,使用 FFT 算法

  • // Chebyshev series coefficients for the SPARSE case
    static const inline std::vector<double> g_coefficientsSparse{
        -0.18646470117093214,   0.036680543700430925,    -0.20323558926782626,     0.029327390306199311,
        -0.24346234149506416,   0.011710240188138248,    -0.27023281815251715,     -0.017621188001030602,
        -0.21383614034992021,   -0.048567932060728937,   -0.013982336571484519,    -0.051097367628344978,
        0.24300487324019346,    0.0016547743046161035,   0.23316923792642233,      0.060707936480887646,
        -0.18317928363421143,   0.0076878773048247966,   -0.24293447776635235,     -0.071417413140564698,
        0.37747441314067182,    0.065154496937795681,    -0.24810721693607704,     -0.033588418808958603,
        0.10510660697380972,    0.012045222815124426,    -0.032574751830745423,    -0.0032761730196023873,
        0.0078689491066424744,  0.00070965574480802061,  -0.0015405394287521192,   -0.00012640521062948649,
        0.00025108496615830787, 0.000018944629154033562, -0.000034753284216308228, -2.4309868106111825e-6,
        4.1486274737866247e-6,  2.7079833113674568e-7,   -4.3245388569898879e-7,   -2.6482744214856919e-8,
        3.9770028771436554e-8,  2.2951153557906580e-9,   -3.2556026220554990e-9,   -1.7691071323926939e-10,
        2.5459052150406730e-10};
    
    // Chebyshev series coefficients for the OPTIMIZED/uniform case
    static const inline std::vector<double> g_coefficientsUniform{
        0.15421426400235561,    -0.0037671538417132409,  0.16032011744533031,      -0.0034539657223742453,
        0.17711481926851286,    -0.0027619720033372291,  0.19949802549604084,      -0.0015928034845171929,
        0.21756948616367638,    0.00010729951647566607,  0.21600427371240055,      0.0022171399198851363,
        0.17647500259573556,    0.0042856217194480991,   0.086174491919472254,     0.0054640252312780444,
        -0.046667988130649173,  0.0047346914623733714,   -0.17712686172280406,     0.0016205080004247200,
        -0.22703114241338604,   -0.0028145845916205865,  -0.13123089730288540,     -0.0056345646688793190,
        0.078818395388692147,   -0.0037868875028868542,  0.23226434602675575,      0.0021116338645426574,
        0.13985510526186795,    0.0059365649669377071,   -0.13918475289368595,     0.0018580676740836374,
        -0.23254376365752788,   -0.0054103844866927788,  0.056840618403875359,     -0.0035227192748552472,
        0.25667909012207590,    0.0055029673963982112,   -0.073334392714092062,    0.0027810273357488265,
        -0.24912792167850559,   -0.0069524866497120566,  0.21288810409948347,      0.0017810057298691725,
        0.088760951809475269,   0.0055957188940032095,   -0.31937177676259115,     -0.0087539416335935556,
        0.34748800245527145,    0.0075378299617709235,   -0.25116537379803394,     -0.0047285674679876204,
        0.13970502851683486,    0.0023672533925155220,   -0.063649401080083698,    -0.00098993213448982727,
        0.024597838934816905,   0.00035553235917057483,  -0.0082485030307578155,   -0.00011176184313622549,
        0.0024390574829093264,  0.000031180384864488629, -0.00064373524734389861,  -7.8036008952377965e-6,
        0.00015310015145922058, 1.7670804180220134e-6,   -0.000033066844379476900, -3.6460909134279425e-7,
        6.5276969021754105e-6,  6.8957843666189918e-8,   -1.1842811187642386e-6,   -1.2015133285307312e-8,
        1.9839339947648331e-7,  1.9372045971100854e-9,   -3.0815418032523593e-8,   -2.9013806338735810e-10,
        4.4540904298173700e-9,  4.0505136697916078e-11,  -6.0104912807134771e-10,  -5.2873323696828491e-12,
        7.5943206779351725e-11, 6.4679566322060472e-13,  -9.0081200925539902e-12,  -7.4396949275292252e-14,
        1.0057423059167244e-12, 8.1701187638005194e-15,  -1.0611736208855373e-13,  -8.9597492970451533e-16,
        1.1421575296031385e-14};
    

    私钥的数据成员,预设的切比雪夫插值系数

scheme-switch

class SWITCHCKKSRNS : public FHERNS,由 FHERNS 派生,实现了 CKKS 和 FHEW 之间的方案切换

  • EvalSchemeSwitchingSetup, EvalSchemeSwitchingKeyGen,方案切换的设置和密钥生成
  • EvalCKKStoFHEWSetup, EvalCKKStoFHEWKeyGen, EvalCKKStoFHEWPrecompute, EvalCKKStoFHEW,从 CKKS 切换到 FHEW
  • EvalFHEWtoCKKSSetup, EvalFHEWtoCKKSKeyGen, EvalFHEWtoCKKSPrecompute, EvalFHEWtoCKKS,从 FHEW 切换到 CKKS
  • EvalCompareSwitchPrecompute, EvalCompareSchemeSwitching,比较
  • EvalMinSchemeSwitching, EvalMinSchemeSwitchingAlt,最大/最小

multiparty

class MultipartyCKKSRNS : public MultipartyRNS,实现了 MultipartyDecryptFusion 以及 Interactive Multi-Party Bootstrapping 的相关函数

  • 15
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值