simple-ckks-bootstrapping.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from openfhe import *
  2. def main():
  3. simple_bootstrap_example()
  4. def simple_bootstrap_example():
  5. parameters = CCParamsCKKSRNS()
  6. secret_key_dist = SecretKeyDist.UNIFORM_TERNARY
  7. parameters.SetSecretKeyDist(secret_key_dist)
  8. parameters.SetSecurityLevel(SecurityLevel.HEStd_NotSet)
  9. parameters.SetRingDim(1<<12)
  10. if get_native_int()==128:
  11. rescale_tech = ScalingTechnique.FIXEDAUTO
  12. dcrt_bits = 78
  13. first_mod = 89
  14. else:
  15. rescale_tech = ScalingTechnique.FLEXIBLEAUTO
  16. dcrt_bits = 59
  17. first_mod = 60
  18. parameters.SetScalingModSize(dcrt_bits)
  19. parameters.SetScalingTechnique(rescale_tech)
  20. parameters.SetFirstModSize(first_mod)
  21. level_budget = [4, 4]
  22. levels_available_after_bootstrap = 10
  23. depth = levels_available_after_bootstrap + FHECKKSRNS.GetBootstrapDepth(level_budget, secret_key_dist)
  24. parameters.SetMultiplicativeDepth(depth)
  25. cryptocontext = GenCryptoContext(parameters)
  26. cryptocontext.Enable(PKESchemeFeature.PKE)
  27. cryptocontext.Enable(PKESchemeFeature.KEYSWITCH)
  28. cryptocontext.Enable(PKESchemeFeature.LEVELEDSHE)
  29. cryptocontext.Enable(PKESchemeFeature.ADVANCEDSHE)
  30. cryptocontext.Enable(PKESchemeFeature.FHE)
  31. ring_dim = cryptocontext.GetRingDimension()
  32. # This is the mazimum number of slots that can be used full packing.
  33. num_slots = int(ring_dim / 2)
  34. print(f"CKKS is using ring dimension {ring_dim}")
  35. cryptocontext.EvalBootstrapSetup(level_budget)
  36. key_pair = cryptocontext.KeyGen()
  37. cryptocontext.EvalMultKeyGen(key_pair.secretKey)
  38. cryptocontext.EvalBootstrapKeyGen(key_pair.secretKey, num_slots)
  39. x = [0.25, 0.5, 0.75, 1.0, 2.0, 3.0, 4.0, 5.0]
  40. encoded_length = len(x)
  41. ptxt = cryptocontext.MakeCKKSPackedPlaintext(x,1,depth-1)
  42. ptxt.SetLength(encoded_length)
  43. print(f"Input: {ptxt}")
  44. ciph = cryptocontext.Encrypt(key_pair.publicKey, ptxt)
  45. print(f"Initial number of levels remaining: {depth - ciph.GetLevel()}")
  46. ciphertext_after = cryptocontext.EvalBootstrap(ciph)
  47. print(f"Number of levels remaining after bootstrapping: {depth - ciphertext_after.GetLevel()}")
  48. result = cryptocontext.Decrypt(ciphertext_after,key_pair.secretKey)
  49. result.SetLength(encoded_length)
  50. print(f"Output after bootstrapping: {result}")
  51. if __name__ == '__main__':
  52. main()