Rener Oliveira (Ubuntu WSL) 2 лет назад
Родитель
Сommit
043786eec4

+ 2 - 5
include/pke/serialization.h

@@ -4,10 +4,7 @@
 #include <pybind11/pybind11.h>
 using namespace lbcrypto;
 
-template <typename T>
-bool SerializeToFileImpl(const std::string& filename, const T& obj, const std::string& sertype_str);
-bool SerializeToFileInterface(const std::string& filename, const CryptoContext<DCRTPoly>& obj, const std::string& sertype_str);
-bool SerializeToFileInterface(const std::string& filename, const PublicKey<DCRTPoly>& obj, const std::string& sertype_str);
-bool SerializeToFileInterface(const std::string& filename, const PrivateKey<DCRTPoly>& obj, const std::string& sertype_str);
+template <typename ST>
+bool SerializeEvalMultKeyWrapper(const std::string& filename, const ST& sertype, std::string id);
 
 #endif // OPENFHE_SERIALIZATION_BINDINGS_H

+ 23 - 8
src/bindings.cpp

@@ -19,12 +19,14 @@ void bind_parameters(py::module &m){
             // getters
             .def("GetPlaintextModulus", &CCParams<CryptoContextBFVRNS>::GetPlaintextModulus)
             .def("GetMultiplicativeDepth", &CCParams<CryptoContextBFVRNS>::GetMultiplicativeDepth);
+    
            
 }
 
 void bind_crypto_context(py::module &m)
 {
-    py::class_<CryptoContextImpl<DCRTPoly>, std::shared_ptr<CryptoContextImpl<DCRTPoly>>>(m, "CryptoContextDCRTPoly")
+    py::class_<CryptoContextImpl<DCRTPoly>, std::shared_ptr<CryptoContextImpl<DCRTPoly>>>(m, "CryptoContext")
+        .def(py::init<>())
         .def("GetKeyGenLevel", &CryptoContextImpl<DCRTPoly>::GetKeyGenLevel)
         .def("SetKeyGenLevel", &CryptoContextImpl<DCRTPoly>::SetKeyGenLevel)
         .def("Enable", static_cast<void (CryptoContextImpl<DCRTPoly>::*)(PKESchemeFeature)>(&CryptoContextImpl<DCRTPoly>::Enable), "Enable a feature for the CryptoContext")
@@ -39,22 +41,34 @@ void bind_crypto_context(py::module &m)
              "Encrypt a plaintext using public key")
         .def("EvalAdd", static_cast<Ciphertext<DCRTPoly> (CryptoContextImpl<DCRTPoly>::*)(ConstCiphertext<DCRTPoly>, ConstCiphertext<DCRTPoly>) const>(&CryptoContextImpl<DCRTPoly>::EvalAdd), "Add two ciphertexts")
         .def("EvalMult", static_cast<Ciphertext<DCRTPoly> (CryptoContextImpl<DCRTPoly>::*)(ConstCiphertext<DCRTPoly>, ConstCiphertext<DCRTPoly>) const>(&CryptoContextImpl<DCRTPoly>::EvalMult), "Multiply two ciphertexts")
-        // lambda function with bool output
-
-           .def_static(
-            "SerializeEvalMultKey", [](const std::string& filename, const SerType::SERBINARY& sertype, std::string id = "")
+        .def_static("ClearEvalMultKeys", [](){
+                CryptoContextImpl<DCRTPoly>::ClearEvalMultKeys();
+            }, "Clear the evaluation keys for multiplication")
+        .def_static("ClearEvalAutomorphismKeys", [](){
+                CryptoContextImpl<DCRTPoly>::ClearEvalAutomorphismKeys();
+            }, "Clear the evaluation keys for rotation")
+        .def_static(
+            "SerializeEvalMultKey", [](const std::string &filename, const SerType::SERBINARY &sertype, std::string id = "")
             {
                 std::ofstream outfile(filename,std::ios::out | std::ios::binary);
                 bool res;
                 res = CryptoContextImpl<DCRTPoly>::SerializeEvalMultKey<SerType::SERBINARY>(outfile, sertype, id);
                 outfile.close();
                 return res; },
-                py::arg("filename"), py::arg("sertype"), py::arg("id") = "",
-            "Serialize an evaluation key for multiplication");
+            py::arg("filename"), py::arg("sertype"), py::arg("id") = "",
+            "Serialize an evaluation key for multiplication")
+            .def_static("SerializeEvalAutomorphismKey", [](const std::string &filename, const SerType::SERBINARY &sertype, std::string id = "")
+            {
+                std::ofstream outfile(filename,std::ios::out | std::ios::binary);
+                bool res;
+                res = CryptoContextImpl<DCRTPoly>::SerializeEvalAutomorphismKey<SerType::SERBINARY>(outfile, sertype, id);
+                outfile.close();
+                return res; },py::arg("filename"), py::arg("sertype"), py::arg("id") = "",  "Serialize evaluation keys for rotation");
 
     // Generator Functions
     m.def("GenCryptoContext", &GenCryptoContext<CryptoContextBFVRNS>);
     m.def("GenCryptoContext", &GenCryptoContext<CryptoContextBGVRNS>);
+    m.def("ReleaseAllContexts",&CryptoContextFactory<DCRTPoly>::ReleaseAllContexts);
 }
 
 void bind_enums_and_constants(py::module &m){
@@ -81,7 +95,8 @@ void bind_enums_and_constants(py::module &m){
 }
 
 void bind_keys(py::module &m){
-    py::class_<PublicKeyImpl<DCRTPoly>,std::shared_ptr<PublicKeyImpl<DCRTPoly>>>(m,"PublicKey");
+    py::class_<PublicKeyImpl<DCRTPoly>,std::shared_ptr<PublicKeyImpl<DCRTPoly>>>(m,"PublicKey")
+    .def(py::init<>());
     py::class_<PrivateKeyImpl<DCRTPoly>,std::shared_ptr<PrivateKeyImpl<DCRTPoly>>>(m,"PrivateKey");
     py::class_<KeyPair<DCRTPoly>>(m,"KeyPair")
             .def_readwrite("publicKey", &KeyPair<DCRTPoly>::publicKey)

+ 2 - 2
src/pke/decryption.cpp

@@ -7,12 +7,12 @@ using namespace lbcrypto;
 namespace py = pybind11;
 
 template<typename Element>
-Plaintext DecryptInterface(Ciphertext<Element> ciphertext,const PrivateKey<Element> privateKey){
+Plaintext DecryptWrapper(Ciphertext<Element> ciphertext,const PrivateKey<Element> privateKey){
     Plaintext plaintextDecResult;
     auto cc = ciphertext->GetCryptoContext();
     cc->Decrypt(privateKey, ciphertext,&plaintextDecResult);
     return plaintextDecResult;
 }
 void bind_decryption(py::module &m){
-    m.def("Decrypt",&DecryptInterface<DCRTPoly>,"Decrypt a ciphertext using private key");
+    m.def("Decrypt",&DecryptWrapper<DCRTPoly>,"Decrypt a ciphertext using private key");
 }

+ 67 - 7
src/pke/examples/simple-integers-serial.py

@@ -20,40 +20,100 @@ cryptoContext.Enable(PKESchemeFeature.LEVELEDSHE)
 # Serialize cryptocontext
 if not SerializeToFile(datafolder + "/cryptocontext.txt", cryptoContext, BINARY):
    raise Exception("Error writing serialization of the crypto context to cryptocontext.txt")
-
 print("The cryptocontext has been serialized.")
 
 # Sample Program: Step 2: Key Generation
 
 # Generate a public/private key pair
 keypair = cryptoContext.KeyGen()
-
 print("The keypair has been generated.")
 
 # Serialize the public key
 if not SerializeToFile(datafolder + "/key-public.txt", keypair.publicKey, BINARY):
    raise Exception("Error writing serialization of the public key to key-public.txt")
-
 print("The public key has been serialized.")
 
 # Serialize the secret key
 if not SerializeToFile(datafolder + "/key-secret.txt", keypair.secretKey, BINARY):
    raise Exception("Error writing serialization of the secret key to key-secret.txt")
-
 print("The secret key has been serialized.")
 
 # Generate the relinearization key
 cryptoContext.EvalMultKeyGen(keypair.secretKey)
-
 print("The relinearization key has been generated.")
 
 # Serialize the relinearization key
-
 if not cryptoContext.SerializeEvalMultKey(datafolder + "/key-relin.txt",BINARY):
    raise Exception("Error writing serialization of the eval mult keys to \"key-eval-mult.txt\"")
-
 print("The relinearization key has been serialized.")
 
+# Generate the rotation evaluation keys
+cryptoContext.EvalRotateKeyGen(keypair.secretKey, [1, 2, -1, -2])
+print("The rotation evaluation keys have been generated.")
+
+# Serialize the rotation evaluation keys
+if not cryptoContext.SerializeEvalAutomorphismKey(datafolder + "/key-eval-rot.txt",BINARY):
+   raise Exception("Error writing serialization of the eval rotate keys to \"key-eval-rot.txt\"")
+print("The rotation evaluation keys have been serialized.")
+
+# Sample Program: Step 3: Encryption
+
+# First plaintext vector is encoded
+vectorOfInts1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
+plaintext1 = cryptoContext.MakePackedPlaintext(vectorOfInts1)
+
+# Second plaintext vector is encoded
+vectorOfInts2 = [3, 2, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12]
+plaintext2 = cryptoContext.MakePackedPlaintext(vectorOfInts2)
+
+# Third plaintext vector is encoded
+vectorOfInts3 = [1, 2, 5, 2, 5, 6, 7, 8, 9, 10, 11, 12]
+plaintext3 = cryptoContext.MakePackedPlaintext(vectorOfInts3)
+
+
+# The encoded vectors are encrypted
+ciphertext1 = cryptoContext.Encrypt(keypair.publicKey, plaintext1)
+ciphertext2 = cryptoContext.Encrypt(keypair.publicKey, plaintext2)
+ciphertext3 = cryptoContext.Encrypt(keypair.publicKey, plaintext3)
+print("The plaintexts have been encrypted.")
+
+if not SerializeToFile(datafolder + "/ciphertext1.txt", ciphertext1, BINARY):
+   raise Exception("Error writing serialization of ciphertext 1 to ciphertext1.txt")
+print("The first ciphertext has been serialized.")
+
+if not SerializeToFile(datafolder + "/ciphertext2.txt", ciphertext2, BINARY):
+   raise Exception("Error writing serialization of ciphertext2 to ciphertext2.txt")
+print("The second ciphertext has been serialized.")
+
+if not SerializeToFile(datafolder + "/ciphertext3.txt", ciphertext3, BINARY):   
+   raise Exception("Error writing serialization of ciphertext3 to ciphertext3.txt")
+print("The third ciphertext has been serialized.")
+
+# Sample Program: Step 4: Evaluation
+
+# OpenFHE maintains an internal map of CryptoContext objects which are
+# indexed by a tag and the tag is applied to both the CryptoContext and some
+# of the keys. When deserializing a context, OpenFHE checks for the tag and
+# if it finds it in the CryptoContext map, it will return the stored version.
+# Hence, we need to clear the context and clear the keys.
+cryptoContext.ClearEvalMultKeys()
+cryptoContext.ClearEvalAutomorphismKeys()
+ReleaseAllContexts()
+
+# Deserialize the crypto context
+cc = CryptoContext()
+
+if not DeserializeFromFile(datafolder + "/cryptocontext.txt", cc, BINARY):
+   raise Exception("Error reading serialization of the crypto context from cryptocontext.txt")
+print("The cryptocontext has been deserialized.")
+
+# Deserialize the public key
+pk = PublicKey()
+
+if not DeserializeFromFile(datafolder + "/key-public.txt", pk, BINARY):
+   raise Exception("Error reading serialization of the public key from key-public.txt")
+
+
 
 
 

+ 16 - 0
src/pke/serialization.cpp

@@ -9,16 +9,32 @@
 using namespace lbcrypto;
 namespace py = pybind11;
 
+template <typename ST>
+bool SerializeEvalMultKeyWrapper(const std::string& filename, const ST& sertype, std::string id)
+{
+    std::ofstream outfile(filename, std::ios::out | std::ios::binary);
+    bool res;
+    res = CryptoContextImpl<DCRTPoly>::SerializeEvalMultKey<ST>(outfile, sertype, id);
+    outfile.close();
+    return res;
+}
 
 void bind_serialization(pybind11::module &m) {
     // Json Serialization
     m.def("SerializeToFile", static_cast<bool (*)(const std::string&, const CryptoContext<DCRTPoly>&, const SerType::SERJSON&)>(&Serial::SerializeToFile<DCRTPoly>), py::arg("filename"), py::arg("obj"), py::arg("sertype"));
+    m.def("DeserializeFromFile", static_cast<bool (*)(const std::string&, CryptoContext<DCRTPoly>& ,const SerType::SERJSON&)>(&Serial::DeserializeFromFile<DCRTPoly>), py::arg("filename"), py::arg("obj"), py::arg("sertype"));
     m.def("SerializeToFile", static_cast<bool (*)(const std::string&, const PublicKey<DCRTPoly>&, const SerType::SERJSON&)>(&Serial::SerializeToFile<PublicKey<DCRTPoly>>), py::arg("filename"), py::arg("obj"), py::arg("sertype"));
+    m.def("DeserializeFromFile", static_cast<bool (*)(const std::string&, PublicKey<DCRTPoly>& ,const SerType::SERJSON&)>(&Serial::DeserializeFromFile<PublicKey<DCRTPoly>>), py::arg("filename"), py::arg("obj"), py::arg("sertype"));
     m.def("SerializeToFile", static_cast<bool (*)(const std::string&, const PrivateKey<DCRTPoly>&, const SerType::SERJSON&)>(&Serial::SerializeToFile<PrivateKey<DCRTPoly>>), py::arg("filename"), py::arg("obj"), py::arg("sertype"));
+    m.def("SerializeToFile", static_cast<bool (*)(const std::string&, const Ciphertext<DCRTPoly>&, const SerType::SERJSON&)>(&Serial::SerializeToFile<Ciphertext<DCRTPoly>>), py::arg("filename"), py::arg("obj"), py::arg("sertype"));
     // Binary Serialization
     m.def("SerializeToFile", static_cast<bool (*)(const std::string&, const CryptoContext<DCRTPoly>&, const SerType::SERBINARY&)>(&Serial::SerializeToFile<DCRTPoly>), py::arg("filename"), py::arg("obj"), py::arg("sertype"));
+    m.def("DeserializeFromFile", static_cast<bool (*)(const std::string&, CryptoContext<DCRTPoly>& ,const SerType::SERBINARY&)>(&Serial::DeserializeFromFile<DCRTPoly>), py::arg("filename"), py::arg("obj"), py::arg("sertype"));
     m.def("SerializeToFile", static_cast<bool (*)(const std::string&, const PublicKey<DCRTPoly>&, const SerType::SERBINARY&)>(&Serial::SerializeToFile<PublicKey<DCRTPoly>>), py::arg("filename"), py::arg("obj"), py::arg("sertype"));
+    m.def("DeserializeFromFile", static_cast<bool (*)(const std::string&, PublicKey<DCRTPoly>& ,const SerType::SERBINARY&)>(&Serial::DeserializeFromFile<PublicKey<DCRTPoly>>), py::arg("filename"), py::arg("obj"), py::arg("sertype"));
     m.def("SerializeToFile", static_cast<bool (*)(const std::string&, const PrivateKey<DCRTPoly>&, const SerType::SERBINARY&)>(&Serial::SerializeToFile<PrivateKey<DCRTPoly>>), py::arg("filename"), py::arg("obj"), py::arg("sertype"));
+    m.def("SerializeToFile", static_cast<bool (*)(const std::string&, const Ciphertext<DCRTPoly>&, const SerType::SERBINARY&)>(&Serial::SerializeToFile<Ciphertext<DCRTPoly>>), py::arg("filename"), py::arg("obj"), py::arg("sertype"));
+    
     
 }