boolean-ap.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from openfhe import *
  2. ## Sample Program: Step 1: Set CryptoContext
  3. cc = BinFHEContext()
  4. """
  5. STD128 is the security level of 128 bits of security based on LWE Estimator
  6. and HE standard. Other common options are TOY, MEDIUM, STD192, and STD256.
  7. MEDIUM corresponds to the level of more than 100 bits for both quantum and
  8. classical computer attacks. The second argument is the bootstrapping method
  9. (AP or GINX). The default method is GINX. Here we explicitly set AP. GINX
  10. typically provides better performance: the bootstrapping key is much
  11. smaller in GINX (by 20x) while the runtime is roughly the same.
  12. """
  13. cc.GenerateBinFHEContext(STD128,AP)
  14. ## Sample Program: Step 2: Key Generation
  15. # Generate the secret key
  16. sk = cc.KeyGen()
  17. print("Generating the bootstrapping keys...\n")
  18. # Generate the bootstrapping keys (refresh and switching keys)
  19. cc.BTKeyGen(sk)
  20. print("Completed the key generation.\n")
  21. # Sample Program: Step 3: Encryption
  22. """
  23. Encrypt two ciphertexts representing Boolean True (1).
  24. By default, freshly encrypted ciphertexts are bootstrapped.
  25. If you wish to get a fresh encryption without bootstrapping, write
  26. ct1 = cc.Encrypt(sk, 1, FRESH)
  27. """
  28. ct1 = cc.Encrypt(sk, 1)
  29. ct2 = cc.Encrypt(sk, 1)
  30. # Sample Program: Step 4: Evaluation
  31. # Compute (1 AND 1) = 1; Other binary gate options are OR, NAND, and NOR
  32. ctAND1 = cc.EvalBinGate(AND, ct1, ct2)
  33. # Compute (NOT 1) = 0
  34. ct2Not = cc.EvalNOT(ct2)
  35. # Compute (1 AND (NOT 1)) = 0
  36. ctAND2 = cc.EvalBinGate(AND, ct2Not, ct1)
  37. # Compute OR of the result in ctAND1 and ctAND2
  38. ctResult = cc.EvalBinGate(OR, ctAND1, ctAND2)
  39. # Sample Program: Step 5: Decryption
  40. result = cc.Decrypt(sk, ctResult)
  41. print(f"Result of encrypted computation of (1 AND 1) OR (1 AND (NOT 1)) = {result}")