simple-real-numbers.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. from openfhe import *
  2. mult_depth = 1
  3. scale_mod_size = 50
  4. batch_size = 8
  5. parameters = CCParamsCKKSRNS()
  6. parameters.SetMultiplicativeDepth(mult_depth)
  7. parameters.SetScalingModSize(scale_mod_size)
  8. parameters.SetBatchSize(batch_size)
  9. cc = GenCryptoContext(parameters)
  10. cc.Enable(PKESchemeFeature.PKE)
  11. cc.Enable(PKESchemeFeature.KEYSWITCH)
  12. cc.Enable(PKESchemeFeature.LEVELEDSHE)
  13. print("The CKKS scheme is using ring dimension: " + str(cc.GetRingDimension()))
  14. keys = cc.KeyGen()
  15. cc.EvalMultKeyGen(keys.secretKey)
  16. cc.EvalRotateKeyGen(keys.secretKey, [1, -2])
  17. x1 = [0.25, 0.5, 0.75, 1.0, 2.0, 3.0, 4.0, 5.0]
  18. x2 = [5.0, 4.0, 3.0, 2.0, 1.0, 0.75, 0.5, 0.25]
  19. ptx1 = cc.MakeCKKSPackedPlaintext(x1)
  20. ptx2 = cc.MakeCKKSPackedPlaintext(x2)
  21. print("Input x1: " + str(ptx1))
  22. print("Input x2: " + str(ptx2))
  23. # Encrypt the encoded vectors
  24. c1 = cc.Encrypt(keys.publicKey, ptx1)
  25. c2 = cc.Encrypt(keys.publicKey, ptx2)
  26. # Step 4: Evaluation
  27. # Homomorphic additions
  28. c_add = cc.EvalAdd(c1, c2)
  29. # Homomorphic subtraction
  30. c_sub = cc.EvalSub(c1, c2)
  31. # Homomorphic scalar multiplication
  32. c_scalar = cc.EvalMult(c1,4)
  33. # Homomorphic multiplication
  34. c_mult = cc.EvalMult(c1, c2)
  35. # Homomorphic rotations
  36. c_rot1 = cc.EvalRotate(c1, 1)
  37. c_rot2 = cc.EvalRotate(c1, -2)
  38. # Step 5: Decryption and output
  39. # Decrypt the result of additions
  40. ptAdd = cc.Decrypt(c_add,keys.secretKey)
  41. # We set the precision to 8 decimal digits for a nicer output.
  42. # If you want to see the error/noise introduced by CKKS, bump it up
  43. # to 15 and it should become visible.
  44. precision = 8
  45. print("Results of homomorphic computations:")
  46. result = cc.Decrypt(c1, keys.secretKey)
  47. result.SetLength(batch_size)
  48. print("x1 = " + str(result))
  49. print("Estimated precision in bits: " + str(result.GetLogPrecision()))
  50. # Decrypt the result of scalar multiplication
  51. result = cc.Decrypt(c_scalar,keys.secretKey)
  52. result.SetLength(batch_size)
  53. print("4 * x1 = " + str(result))
  54. # Decrypt the result of multiplication
  55. result = cc.Decrypt(c_mult,keys.secretKey)
  56. result.SetLength(batch_size)
  57. print("x1 * x2 = " + str(result))
  58. # Decrypt the result of rotations
  59. result = cc.Decrypt(c_rot1,keys.secretKey)
  60. result.SetLength(batch_size)
  61. print("In rotations, very small outputs (~10^-10 here) correspond to 0's:")
  62. print("x1 rotated by 1 = " + str(result))
  63. result = cc.Decrypt(c_rot2,keys.secretKey)
  64. result.SetLength(batch_size)
  65. print("x1 rotated by -2 = " + str(result))