polynomial-evaluation.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from openfhe import *
  2. import time
  3. def main():
  4. print("\n======EXAMPLE FOR EVALPOLY========\n")
  5. parameters = CCParamsCKKSRNS()
  6. parameters.SetMultiplicativeDepth(6)
  7. parameters.SetScalingModSize(50)
  8. cc = GenCryptoContext(parameters)
  9. cc.Enable(PKESchemeFeature.PKE)
  10. cc.Enable(PKESchemeFeature.KEYSWITCH)
  11. cc.Enable(PKESchemeFeature.LEVELEDSHE)
  12. cc.Enable(PKESchemeFeature.ADVANCEDSHE)
  13. input = [complex(a,0) for a in [0.5, 0.7, 0.9, 0.95, 0.93]]
  14. # input = [0.5, 0.7, 0.9, 0.95, 0.93]
  15. encoded_length = len(input)
  16. coefficients1 = [0.15, 0.75, 0, 1.25, 0, 0, 1, 0, 1, 2, 0, 1, 0, 0, 0, 0, 1]
  17. coefficients2 = [1, 2, 3, 4, 5, -1, -2, -3, -4, -5,
  18. 0.1, 0.2, 0.3, 0.4, 0.5, -0.1, -0.2, -0.3, -0.4, -0.5,
  19. 0.1, 0.2, 0.3, 0.4, 0.5, -0.1, -0.2, -0.3, -0.4, -0.5]
  20. plaintext1 = cc.MakeCKKSPackedPlaintext(input)
  21. key_pair = cc.KeyGen()
  22. print("Generating evaluation key for homomorphic multiplication...")
  23. cc.EvalMultKeyGen(key_pair.secretKey)
  24. print("Completed.\n")
  25. ciphertext1 = cc.Encrypt(key_pair.publicKey, plaintext1)
  26. t = time.time()
  27. result = cc.EvalPoly(ciphertext1, coefficients1)
  28. time_eval_poly1 = time.time() - t
  29. t = time.time()
  30. result2 = cc.EvalPoly(ciphertext1, coefficients2)
  31. time_eval_poly2 = time.time() - t
  32. plaintext_dec = cc.Decrypt(result, key_pair.secretKey)
  33. plaintext_dec.SetLength(encoded_length)
  34. plaintext_dec2 = cc.Decrypt(result2, key_pair.secretKey)
  35. plaintext_dec2.SetLength(encoded_length)
  36. print("\n Original Plaintext #1: \n")
  37. print(plaintext1)
  38. print(f"\n Result of evaluating a polynomial with coefficients {coefficients1}: \n")
  39. print(plaintext_dec)
  40. print("\n Expected result: (0.70519107, 1.38285078, 3.97211180, "
  41. "5.60215665, 4.86357575) \n")
  42. print(f"\n Evaluation time: {time_eval_poly1*1000} ms \n")
  43. print(f"\n Result of evaluating a polynomial with coefficients {coefficients2}: \n")
  44. print(plaintext_dec2)
  45. print("\n Expected result: (3.4515092326, 5.3752765397, 4.8993108833, "
  46. "3.2495023573, 4.0485229982) \n")
  47. print(f"\n Evaluation time: {time_eval_poly2*1000} ms \n")
  48. if __name__ == '__main__':
  49. main()