simple-integers-serial.py 7.5 KB

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