test_boolean.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from openfhe import *
  2. import pytest
  3. ## Sample Program: Step 1: Set CryptoContext
  4. @pytest.mark.parametrize("context",[TOY,MEDIUM,STD128])
  5. @pytest.mark.parametrize("a", [0, 1])
  6. @pytest.mark.parametrize("b", [0, 1])
  7. def test_boolean_AND(context,a, b):
  8. cc = BinFHEContext()
  9. """
  10. STD128 is the security level of 128 bits of security based on LWE Estimator
  11. and HE standard. Other common options are TOY, MEDIUM, STD192, and STD256.
  12. MEDIUM corresponds to the level of more than 100 bits for both quantum and
  13. classical computer attacks
  14. """
  15. cc.GenerateBinFHEContext(context, GINX)
  16. ## Sample Program: Step 2: Key Generation
  17. # Generate the secret key
  18. sk = cc.KeyGen()
  19. assert sk.GetLength() == len(sk)
  20. print("Generating the bootstrapping keys...\n")
  21. # Generate the bootstrapping keys (refresh and switching keys)
  22. cc.BTKeyGen(sk)
  23. # Sample Program: Step 3: Encryption
  24. """
  25. Encrypt two ciphertexts representing Boolean True (1).
  26. By default, freshly encrypted ciphertexts are bootstrapped.
  27. If you wish to get a fresh encryption without bootstrapping, write
  28. ct1 = cc.Encrypt(sk, 1, FRESH)
  29. """
  30. ct1 = cc.Encrypt(sk, a)
  31. ct2 = cc.Encrypt(sk, b)
  32. assert ct1.GetLength() == len(ct1)
  33. # Sample Program: Step 4: Evaluation
  34. # Compute (1 AND 1) = 1; Other binary gate options are OR, NAND, and NOR
  35. ctAND1 = cc.EvalBinGate(AND, ct1, ct2)
  36. # Compute (NOT 1) = 0
  37. ct2Not = cc.EvalNOT(ct2)
  38. # Compute (1 AND (NOT 1)) = 0
  39. ctAND2 = cc.EvalBinGate(AND, ct2Not, ct1)
  40. # Compute OR of the result in ctAND1 and ctAND2
  41. ctResult = cc.EvalBinGate(OR, ctAND1, ctAND2)
  42. # Sample Program: Step 5: Decryption
  43. result = cc.Decrypt(sk, ctResult)
  44. print(
  45. f"Result of encrypted computation of ({a} AND {b}) OR ({a} AND (NOT {b})) = {result}"
  46. )
  47. plaintext_result = (a and b) or (a and (not b))
  48. assert (
  49. result == plaintext_result
  50. ), "Logical AND in plaintext and ciphertext should be same"