simple-integers-serial-bgvrns.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. # Initial Settings
  2. from openfhe import *
  3. import tempfile
  4. import os
  5. # import openfhe.PKESchemeFeature as Feature
  6. datafolder = "demoData"
  7. def main_action():
  8. serType = BINARY # BINARY or JSON
  9. print(
  10. "This program requres the subdirectory `"
  11. + datafolder
  12. + "' to exist, otherwise you will get an error writing serializations."
  13. )
  14. # Sample Program: Step 1: Set CryptoContext
  15. parameters = CCParamsBGVRNS()
  16. parameters.SetPlaintextModulus(65537)
  17. parameters.SetMultiplicativeDepth(2)
  18. cryptoContext = GenCryptoContext(parameters)
  19. # Enable features that you wish to use
  20. cryptoContext.Enable(PKESchemeFeature.PKE)
  21. cryptoContext.Enable(PKESchemeFeature.KEYSWITCH)
  22. cryptoContext.Enable(PKESchemeFeature.LEVELEDSHE)
  23. # Serialize cryptocontext
  24. if not SerializeToFile(datafolder + "/cryptocontext.txt", cryptoContext, serType):
  25. raise Exception(
  26. "Error writing serialization of the crypto context to cryptocontext.txt"
  27. )
  28. print("The cryptocontext has been serialized.")
  29. # Sample Program: Step 2: Key Generation
  30. # Generate a public/private key pair
  31. keypair = cryptoContext.KeyGen()
  32. print("The keypair has been generated.")
  33. # Serialize the public key
  34. if not SerializeToFile(datafolder + "/key-public.txt", keypair.publicKey, serType):
  35. raise Exception(
  36. "Error writing serialization of the public key to key-public.txt"
  37. )
  38. print("The public key has been serialized.")
  39. # Serialize the secret key
  40. if not SerializeToFile(datafolder + "/key-private.txt", keypair.secretKey, serType):
  41. raise Exception(
  42. "Error writing serialization of the secret key to key-private.txt"
  43. )
  44. print("The secret key has been serialized.")
  45. # Generate the relinearization key
  46. cryptoContext.EvalMultKeyGen(keypair.secretKey)
  47. print("The relinearization key has been generated.")
  48. # Serialize the relinearization key
  49. if not cryptoContext.SerializeEvalMultKey(
  50. datafolder + "/key-eval-mult.txt", serType
  51. ):
  52. raise Exception(
  53. 'Error writing serialization of the eval mult keys to "key-eval-mult.txt"'
  54. )
  55. print("The relinearization key has been serialized.")
  56. # Generate the rotation evaluation keys
  57. cryptoContext.EvalRotateKeyGen(keypair.secretKey, [1, 2, -1, -2])
  58. print("The rotation evaluation keys have been generated.")
  59. # Serialize the rotation evaluation keys
  60. if not cryptoContext.SerializeEvalAutomorphismKey(
  61. datafolder + "/key-eval-rot.txt", serType
  62. ):
  63. raise Exception(
  64. 'Error writing serialization of the eval rotate keys to "key-eval-rot.txt"'
  65. )
  66. print("The rotation evaluation keys have been serialized.")
  67. # Sample Program: Step 3: Encryption
  68. # First plaintext vector is encoded
  69. vectorOfInts1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  70. plaintext1 = cryptoContext.MakePackedPlaintext(vectorOfInts1)
  71. # Second plaintext vector is encoded
  72. vectorOfInts2 = [3, 2, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  73. plaintext2 = cryptoContext.MakePackedPlaintext(vectorOfInts2)
  74. # Third plaintext vector is encoded
  75. vectorOfInts3 = [1, 2, 5, 2, 5, 6, 7, 8, 9, 10, 11, 12]
  76. plaintext3 = cryptoContext.MakePackedPlaintext(vectorOfInts3)
  77. # The encoded vectors are encrypted
  78. ciphertext1 = cryptoContext.Encrypt(keypair.publicKey, plaintext1)
  79. ciphertext2 = cryptoContext.Encrypt(keypair.publicKey, plaintext2)
  80. ciphertext3 = cryptoContext.Encrypt(keypair.publicKey, plaintext3)
  81. print("The plaintexts have been encrypted.")
  82. if not SerializeToFile(datafolder + "/ciphertext1.txt", ciphertext1, serType):
  83. raise Exception(
  84. "Error writing serialization of ciphertext 1 to ciphertext1.txt"
  85. )
  86. print("The first ciphertext has been serialized.")
  87. if not SerializeToFile(datafolder + "/ciphertext2.txt", ciphertext2, serType):
  88. raise Exception("Error writing serialization of ciphertext2 to ciphertext2.txt")
  89. print("The second ciphertext has been serialized.")
  90. if not SerializeToFile(datafolder + "/ciphertext3.txt", ciphertext3, serType):
  91. raise Exception("Error writing serialization of ciphertext3 to ciphertext3.txt")
  92. print("The third ciphertext has been serialized.")
  93. # Sample Program: Step 4: Evaluation
  94. # OpenFHE maintains an internal map of CryptoContext objects which are
  95. # indexed by a tag and the tag is applied to both the CryptoContext and some
  96. # of the keys. When deserializing a context, OpenFHE checks for the tag and
  97. # if it finds it in the CryptoContext map, it will return the stored version.
  98. # Hence, we need to clear the context and clear the keys.
  99. ClearEvalMultKeys()
  100. cryptoContext.ClearEvalAutomorphismKeys()
  101. ReleaseAllContexts()
  102. # Deserialize the crypto context
  103. cc, res = DeserializeCryptoContext(datafolder + "/cryptocontext.txt", serType)
  104. if not res:
  105. raise Exception(
  106. "Error reading serialization of the crypto context from cryptocontext.txt"
  107. )
  108. print("The cryptocontext has been deserialized.")
  109. # Deserialize the public key
  110. pk, res = DeserializePublicKey(datafolder + "/key-public.txt", serType)
  111. if not res:
  112. raise Exception(
  113. "Error reading serialization of the public key from key-public.txt"
  114. )
  115. print("The public key has been deserialized.")
  116. if not cc.DeserializeEvalMultKey(datafolder + "/key-eval-mult.txt", serType):
  117. raise Exception("Could not deserialize the eval mult key file")
  118. print("The relinearization key has been deserialized.")
  119. if not cc.DeserializeEvalAutomorphismKey(datafolder + "/key-eval-rot.txt", serType):
  120. raise Exception("Could not deserialize the eval rotation key file")
  121. print("Deserialized the eval rotation keys.")
  122. # Deserialize the ciphertexts
  123. ct1, res = DeserializeCiphertext(datafolder + "/ciphertext1.txt", serType)
  124. if not res:
  125. raise Exception("Could not read the ciphertext")
  126. print("The first ciphertext has been deserialized.")
  127. ct2, res = DeserializeCiphertext(datafolder + "/ciphertext2.txt", serType)
  128. if not res:
  129. raise Exception("Could not read the ciphertext")
  130. print("The second ciphertext has been deserialized.")
  131. ct3, res = DeserializeCiphertext(datafolder + "/ciphertext3.txt", serType)
  132. if not res:
  133. raise Exception("Could not read the ciphertext")
  134. print("The third ciphertext has been deserialized.")
  135. # Homomorphic addition
  136. ciphertextAdd12 = cc.EvalAdd(ct1, ct2)
  137. ciphertextAddResult = cc.EvalAdd(ciphertextAdd12, ct3)
  138. # Homomorphic multiplication
  139. ciphertextMult12 = cc.EvalMult(ct1, ct2)
  140. ciphertextMultResult = cc.EvalMult(ciphertextMult12, ct3)
  141. # Homomorphic rotation
  142. ciphertextRot1 = cc.EvalRotate(ct1, 1)
  143. ciphertextRot2 = cc.EvalRotate(ct2, 2)
  144. ciphertextRot3 = cc.EvalRotate(ct3, -1)
  145. ciphertextRot4 = cc.EvalRotate(ct3, -2)
  146. # Sample Program: Step 5: Decryption
  147. sk, res = DeserializePrivateKey(datafolder + "/key-private.txt", serType)
  148. if not res:
  149. raise Exception("Could not read secret key")
  150. print("The secret key has been deserialized.")
  151. # Decrypt the result of additions
  152. plaintextAddResult = cc.Decrypt(sk, ciphertextAddResult)
  153. # Decrypt the result of multiplications
  154. plaintextMultResult = cc.Decrypt(sk, ciphertextMultResult)
  155. # Decrypt the result of rotations
  156. plaintextRot1 = cc.Decrypt(sk, ciphertextRot1)
  157. plaintextRot2 = cc.Decrypt(sk, ciphertextRot2)
  158. plaintextRot3 = cc.Decrypt(sk, ciphertextRot3)
  159. plaintextRot4 = cc.Decrypt(sk, ciphertextRot4)
  160. # Shows only the same number of elements as in the original plaintext vector
  161. # By default it will show all coefficients in the BFV-encoded polynomial
  162. plaintextRot1.SetLength(len(vectorOfInts1))
  163. plaintextRot2.SetLength(len(vectorOfInts1))
  164. plaintextRot3.SetLength(len(vectorOfInts1))
  165. plaintextRot4.SetLength(len(vectorOfInts1))
  166. # Output results
  167. print("\nResults of homomorphic computations")
  168. print("#1 + #2 + #3: " + str(plaintextAddResult))
  169. print("#1 * #2 * #3: " + str(plaintextMultResult))
  170. print("Left rotation of #1 by 1: " + str(plaintextRot1))
  171. print("Left rotation of #1 by 2: " + str(plaintextRot2))
  172. print("Right rotation of #1 by 1: " + str(plaintextRot3))
  173. print("Right rotation of #1 by 2: " + str(plaintextRot4))
  174. def main():
  175. global datafolder
  176. with tempfile.TemporaryDirectory() as td:
  177. datafolder = td + "/" + datafolder
  178. os.mkdir(datafolder)
  179. main_action()
  180. if __name__ == "__main__":
  181. main()