コード例 #1
0
    def test_Pyfhel_4a_operations_integer(self):
        pyfhel = Pyfhel()
        pyfhel.contextGen(p=1964769281, m=8192, base=3, sec=192)
        pyfhel.keyGen()
        # self.pyfhel.rotateKeyGen(60)
        # self.pyfhel.relinKeyGen(60)

        ctxti = pyfhel.encryptInt(127)
        ctxti2 = pyfhel.encryptInt(-2)
        ptxti = pyfhel.encodeInt(3)

        ctxt_add = pyfhel.add(ctxti, ctxti2, in_new_ctxt=True)
        ctxt_add2 = pyfhel.add_plain(ctxti, ptxti, in_new_ctxt=True)
        ctxt_sub = pyfhel.sub(ctxti, ctxti2, in_new_ctxt=True)
        ctxt_sub2 = pyfhel.sub_plain(ctxti, ptxti, in_new_ctxt=True)
        ctxt_mult = pyfhel.multiply(ctxti, ctxti2, in_new_ctxt=True)
        ctxt_mult2 = pyfhel.multiply_plain(ctxti, ptxti, in_new_ctxt=True)
        # self.ctxt_rotate = self.pyfhel.rotate(self.ctxti, 2)
        # self.ctxt_expon = self.pyfhel.power(self.ctxti, 3)
        # self.ctxt_expon2 = self.pyfhel.power(self.ctxti2, 3)
        # self.ctxt_polyEval = self.pyfhel.polyEval(self.ctxti, [1, 2, 1], in_new_ctxt=True)

        self.assertEqual(pyfhel.decryptInt(ctxt_add), 125)
        self.assertEqual(pyfhel.decryptInt(ctxt_add2), 130)
        self.assertEqual(pyfhel.decryptInt(ctxt_sub), 129)
        self.assertEqual(pyfhel.decryptInt(ctxt_sub2), 124)
        self.assertEqual(pyfhel.decryptInt(ctxt_mult), -254)
        self.assertEqual(pyfhel.decryptInt(ctxt_mult2), 381)
コード例 #2
0
 def test_Pyfhel_3a_encrypt_decrypt_int(self):
     pyfhel = Pyfhel()
     pyfhel.contextGen(p=65537)
     pyfhel.keyGen()
     ctxt = pyfhel.encryptInt(127)
     self.assertEqual(pyfhel.decryptInt(ctxt), 127)
     ctxt2 = PyCtxt(ctxt)
     pyfhel.encryptInt(-2, ctxt)
     self.assertEqual(pyfhel.decryptInt(ctxt), -2)
     self.assertEqual(pyfhel.decryptInt(ctxt), -2)
     self.assertEqual(pyfhel.decryptInt(ctxt2), 127)
コード例 #3
0
ファイル: test.py プロジェクト: jeremykohn/Pyfhel
    def test_Pyfhel_5c_save_restore_all(self):
        pyfhel = Pyfhel()
        pyfhel.contextGen(p=1964769281,
                          m=8192,
                          base=2,
                          sec=192,
                          flagBatching=True)
        pyfhel.keyGen()
        pyfhel.rotateKeyGen(60)
        pyfhel.relinKeyGen(60, 4)
        # save all keys into temporary directory
        tmp_dir = tempfile.TemporaryDirectory()
        pyfhel.saveContext(tmp_dir.name + "/context")
        pyfhel.savepublicKey(tmp_dir.name + "/pub.key")
        pyfhel.savesecretKey(tmp_dir.name + "/sec.key")
        pyfhel.saverelinKey(tmp_dir.name + "/relin.key")
        pyfhel.saverotateKey(tmp_dir.name + "/rotate.key")
        # restore all keys
        pyfhel2 = Pyfhel()
        pyfhel.contextGen(p=1964769281,
                          m=8192,
                          base=2,
                          sec=192,
                          flagBatching=True)
        pyfhel2.restoreContext(tmp_dir.name + "/context")
        pyfhel2.restorepublicKey(tmp_dir.name + "/pub.key")
        pyfhel2.restoresecretKey(tmp_dir.name + "/sec.key")
        pyfhel2.restorerelinKey(tmp_dir.name + "/relin.key")
        pyfhel2.restorerotateKey(tmp_dir.name + "/rotate.key")

        # test encryption decryption
        ctxt1 = pyfhel.encryptBatch([42])
        self.assertEqual(
            pyfhel2.decryptBatch(ctxt1)[0],
            42,
            "decrypting with restored keys should work",
        )
        try:
            pyfhel2.rotate(ctxt1, -1)
            self.assertEqual(
                pyfhel2.decryptBatch(ctxt1)[1],
                42,
                "decrypting with restored keys should work",
            )
        except Exception as err:
            self.fail("PyPtxt() creation failed unexpectedly: ", err)

        # test ciphertext storing
        ctxt2 = pyfhel.encryptInt(42)
        ctxt2.save(tmp_dir.name + "/ctxt2")

        ctxt_restored = PyCtxt()
        ctxt_restored.load(tmp_dir.name + "/ctxt2", "int")
        self.assertEqual(pyfhel2.decryptInt(ctxt_restored), 42,
                         "decrypting ciphertext should work")
        tmp_dir.cleanup()
コード例 #4
0
    def test_Pyfhel_4a_operations_integer(self):
        pyfhel = Pyfhel()
        pyfhel.contextGen(p=1964769281, m=8192, base=3, sec=192)
        pyfhel.keyGen()

        ctxti = pyfhel.encryptInt(127)
        ctxti2 = pyfhel.encryptInt(-2)
        ptxti = pyfhel.encodeInt(3)

        ctxt_add = pyfhel.add(ctxti, ctxti2, in_new_ctxt=True)
        ctxt_add2 = pyfhel.add_plain(ctxti, ptxti, in_new_ctxt=True)
        ctxt_sub = pyfhel.sub(ctxti, ctxti2, in_new_ctxt=True)
        ctxt_sub2 = pyfhel.sub_plain(ctxti, ptxti, in_new_ctxt=True)
        ctxt_mult = pyfhel.multiply(ctxti, ctxti2, in_new_ctxt=True)
        ctxt_mult2 = pyfhel.multiply_plain(ctxti, ptxti, in_new_ctxt=True)

        self.assertEqual(pyfhel.decryptInt(ctxt_add), 125)
        self.assertEqual(pyfhel.decryptInt(ctxt_add2), 130)
        self.assertEqual(pyfhel.decryptInt(ctxt_sub), 129)
        self.assertEqual(pyfhel.decryptInt(ctxt_sub2), 124)
        self.assertEqual(pyfhel.decryptInt(ctxt_mult), -254)
        self.assertEqual(pyfhel.decryptInt(ctxt_mult2), 381)
コード例 #5
0
 def test_Pyfhel_5d_save_restore_int(self):
     pyfhel = Pyfhel()
     pyfhel.contextGen(p=1964769281, m=8192, base=2, sec=192, flagBatching=True)
     pyfhel.keyGen()
     pyfhel.rotateKeyGen(60)
     pyfhel.relinKeyGen(60, 4)
     # encrypt something
     ctxt = pyfhel.encryptInt(42)
     # save to temporary file
     tmp = tempfile.NamedTemporaryFile()
     ctxt.save(tmp.name)
     # load from temporary file
     loaded = PyCtxt()
     loaded.load(tmp.name)
     self.assertEqual(pyfhel.decryptInt(loaded), 42)
コード例 #6
0
 def test_Pyfhel_5d_save_restore_int(self):
     pyfhel = Pyfhel()
     pyfhel.contextGen(p=1964769281, m=8192, base=2, sec=192, flagBatching=True)
     pyfhel.keyGen()
     pyfhel.rotateKeyGen(60)
     pyfhel.relinKeyGen(60, 4)
     # encrypt something
     ctxt = pyfhel.encryptInt(42)
     # save to temporary file
     tmp_dir = tempfile.TemporaryDirectory()
     tmp_file = os.path.join(tmp_dir.name, "ctxt")
     ctxt.save(tmp_file)
     # load from temporary file
     loaded = PyCtxt()
     loaded.load(tmp_file, "int")
     self.assertEqual(pyfhel.decryptInt(loaded), 42)
     tmp_dir.cleanup()
コード例 #7
0
def index():
    if request.method == "POST":
        details = request.form
        firstName = details['fname']
        lastName = details['lname']
        HE = Pyfhel()
        HE.contextGen(p=65537)
        HE.keyGen()
        HE.saveContext('data/Konteks_file')
        HE.savepublicKey('data/kunci_file')
        HE.savesecretKey('data/KunciSec.key')
        c1 = HE.encryptInt(int(firstName))
        q1 = str(c1)
        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO Pengguna(noID,umur) VALUES (%s,%s)",
                    (q1, lastName))
        mysql.connection.commit()
        cur.close()
        q1 = (str(c1)).replace('<', '')
        q1 = q1.replace('>', '')
        return q1
    return render_template('InputUser.html')
コード例 #8
0
from Pyfhel import Pyfhel, PyPtxt, PyCtxt

print("==============================================================")
print("===================== Pyfhel ENCRYPTING ======================")
print("==============================================================")

print("1. Creating Context and KeyGen in a Pyfhel Object ")
HE = Pyfhel()  # Creating empty Pyfhel object
HE.contextGen(p=65537, m=1024, flagBatching=True)  # Generating context.
# The values of p and m are chosen to enable batching (see Demo_Batching_SIMD.py)
HE.keyGen()  # Key Generation.

print("2. Encrypting integers with encryptInt")
integer1 = 94
integer2 = -235
ctxt_i1 = HE.encryptInt(
    integer1)  # Encrypting integer1 in a new PyCtxt with encryptInt
ctxt_i2 = PyCtxt()  # Empty ciphertexts have no encoding type.
print("    Empty created ctxt_i2: ", str(ctxt_i2))
HE.encryptInt(integer2, ctxt_i2)  # Encrypting integer2 in an existing PyCtxt
print("    int ", integer1, '-> ctxt_i1 ', str(ctxt_i1))
print("    int ", integer2, '-> ctxt_i2 ', str(ctxt_i2))

print("3. Encrypting floating point values with encryptFrac")
float1 = 3.5
float2 = -7.8
ctxt_f1 = HE.encryptInt(
    float1)  # Encrypting float1 in a new PyCtxt with encryptFrac
ctxt_f2 = PyCtxt()
HE.encryptFrac(float2, ctxt_f2)  # Encrypting float2 in an existing PyCtxt
print("    float ", float1, '-> ctxt_f1 ', str(ctxt_f1))
print("    float ", float2, '-> ctxt_f2 ', str(ctxt_f2))
コード例 #9
0
HE.relinKeyGen()

print("\nA1. BFV context generation")
print(f"\t{HE}")

# %%
# 2. BFV Array Encoding & Encryption
# -----------------------------------------
# We will define two 1D integer arrays, encode and encrypt them:
# arr1 = [0, 1, ... n-1]
# arr2 = [-t//2, -1, 1, 0, 0..., 0]

arr1 = np.arange(HE.n, dtype=np.int64)
arr2 = np.array([1, -1, 1], dtype=np.int64)

ctxt1 = HE.encryptInt(arr1)
ctxt2 = HE.encryptInt(arr2)

print("\nA2. Integer Encryption")
print("->\tarr1 ", arr1, '\n\t==> ctxt1 ', ctxt1)
print("->\tarr2 ", arr2, '\n\t==> ctxt2 ', ctxt2)

# %%
# 3. BFV: Securely multiplying as much as we can
# -------------------------------------------------
# You can measure the noise level using HE.noise_level(ctxt).
# IMPORTANT! To get the noise Level you need the private key! otherwise the only
# way to know if above the noise is to decrypt the ciphertext and check the result.

print("A3. Securely multiplying as much as we can")
step = 0
コード例 #10
0
                        # The n defines the number of plaintext slots.
                        #  There are many configurable parameters on this step
                        #  More info in Demo_2, Demo_3, and Pyfhel.contextGen()
HE.keyGen()             # Key Generation: generates a pair of public/secret keys
# %%
# The best way to obtain information from a created Pyfhel object is to print it:
print("2. Context and key setup")
print(HE)

# %%
# 3. Integer Encryption
# ---------------------------
# we will define two integers and encrypt them using `encryptInt`:
integer1 = np.array([127], dtype=np.int64)
integer2 = np.array([-2], dtype=np.int64)
ctxt1 = HE.encryptInt(integer1) # Encryption makes use of the public key
ctxt2 = HE.encryptInt(integer2) # For integers, encryptInt function is used.
print("3. Integer Encryption, ")
print("    int ",integer1,'-> ctxt1 ', type(ctxt1))
print("    int ",integer2,'-> ctxt2 ', type(ctxt2))
# %%
# # The best way to obtain information from a ciphertext is to print it:
print(ctxt1)
print(ctxt2)

# %%
# 4. Operating with encrypted integers
# --------------------------------------
# Relying on the context defined before, we will now operate
# (addition, substaction, multiplication) the two ciphertexts:
ctxtSum = ctxt1 + ctxt2         # `ctxt1 += ctxt2` for inplace operation
コード例 #11
0
import base64, os

HE = Pyfhel()  # Creating empty Pyfhel object

#************************************
#Generate test files, run load for the first time
HE.contextGen(p=65537)
HE.keyGen()

HE.saveContext("context.pycon")
HE.savepublicKey("public_k.pypk")
HE.savesecretKey("secret_k.pysk")

integer1 = 20
integer2 = 68
ctxtx = HE.encryptInt(integer1)
ctxty = HE.encryptInt(integer2)
ctxtx.save("ctxt.c1")
ctxty.save("ctxt.c2")
#************************************

with open("context.pycon", "rb") as con_f:
    a = con_f.read() + b"="
    context_b64e = str(base64.b64encode(a), "utf-8")

with open("public_k.pypk", "rb") as pk_f:
    b = pk_f.read() + b"="
    public_b64e = str(base64.b64encode(b), "utf-8")

with open("ctxt.c1", "rb") as c1_f:
    c = c1_f.read() + b"="
コード例 #12
0
ファイル: Demo_Numpy.py プロジェクト: jeremykohn/Pyfhel
#  in the docs of the function (link to docs in README)
HE.keyGen()  # Key Generation.
print(HE)

print("2. Encrypting two arrays of integers.")
print(
    "    For this, you need to create empty arrays in numpy and assign them the cyphertexts"
)
array1 = np.array([1, 3, 5, 7, 9])
array2 = np.array([-2, 4, -6, 8, -10])
arr_ctxt1 = np.empty(len(array1), dtype=PyCtxt)
arr_ctxt2 = np.empty(len(array1), dtype=PyCtxt)

# Encrypting! This can be parallelized!
for i in np.arange(len(array1)):
    arr_ctxt1[i] = HE.encryptInt(array1[i])
    arr_ctxt2[i] = HE.encryptInt(array2[i])

print("    array1: ", array1, '-> ctxt1 ', type(arr_ctxt1), ', dtype:',
      arr_ctxt1.dtype)
print("    array2: ", array2, '-> ctxt2 ', type(arr_ctxt2), ', dtype:',
      arr_ctxt2.dtype)

print("3. Vectorized operations with encrypted arrays of PyCtxt")
ctxtSum = arr_ctxt1 + arr_ctxt2  # `ctxt1 += ctxt2` for quicker inplace operation
ctxtSub = arr_ctxt1 - arr_ctxt2  # `ctxt1 -= ctxt2` for quicker inplace operation
ctxtMul = arr_ctxt1 * arr_ctxt2  # `ctxt1 *= ctxt2` for quicker inplace operation

print("4. Decrypting results:")
resSum = [HE.decryptInt(ctxtSum[i]) for i in np.arange(len(ctxtSum))]
resSub = [HE.decryptInt(ctxtSub[i]) for i in np.arange(len(ctxtSub))]
コード例 #13
0
print("==============================================================")
print("===================== Pyfhel ENCRYPTING ======================")
print("==============================================================")

print("1. Creating Context and KeyGen in a Pyfhel Object ")
HE = Pyfhel()  # Creating empty Pyfhel object
HE.contextGen(p=65537, m=2048, base=3,
              flagBatching=True)  # Generating context.
# The values of p and m are chosen to enable batching (see Demo_Batching_SIMD.py)
HE.keyGen()  # Key Generation.

print("2. Encrypting integers with encryptInt")
integer1 = 94
integer2 = -235
ctxt_i1 = HE.encryptInt(
    integer1)  # Encrypting integer1 in a new PyCtxt with encryptInt
ctxt_i2 = PyCtxt()  # Empty ciphertexts have no encoding type.
print("    Empty created ctxt_i2: ", str(ctxt_i2))
HE.encryptInt(integer2, ctxt_i2)  # Encrypting integer2 in an existing PyCtxt
print("    int ", integer1, '-> ctxt_i1 ', str(ctxt_i1))
print("    int ", integer2, '-> ctxt_i2 ', str(ctxt_i2))

print("3. Encrypting floating point values with encryptFrac")
float1 = 3.5
float2 = -7.8
ctxt_f1 = HE.encryptFrac(
    float1)  # Encrypting float1 in a new PyCtxt with encryptFrac
ctxt_f2 = PyCtxt()
HE.encryptFrac(float2, ctxt_f2)  # Encrypting float2 in an existing PyCtxt
print("    float ", float1, '-> ctxt_f1 ', str(ctxt_f1))
print("    float ", float2, '-> ctxt_f2 ', str(ctxt_f2))
コード例 #14
0
class PyfhelTestCase(unittest.TestCase):
    def setUp(self):
        self.t0 = time.time()

    def tearDown(self):
        sys.stderr.write('({}s) ...'.format(round(time.time() - self.t0, 3)))

    def test_PyPtxt_PyCtxt(self):
        pass

    def test_PyPtxt_creation_deletion(self):
        try:
            self.ptxt = PyPtxt()
            self.ptxt2 = PyPtxt(other_ptxt=self.ptxt)
            self.pyfhel = Pyfhel()
            self.ptxt3 = PyPtxt(pyfhel=self.pyfhel)
            self.ptxt4 = PyPtxt(other_ptxt=self.ptxt3)
        except Exception as err:
            self.fail("PyPtxt() creation failed unexpectedly: ", err)
        self.assertEqual(self.ptxt._encoding, ENCODING_t.UNDEFINED)
        self.ptxt._encoding = ENCODING_t.INTEGER
        self.assertEqual(self.ptxt._encoding, ENCODING_t.INTEGER)
        del (self.ptxt._encoding)
        self.assertEqual(self.ptxt._encoding, ENCODING_t.UNDEFINED)
        self.ptxt._pyfhel = self.pyfhel
        self.ptxt2._pyfhel = self.ptxt._pyfhel
        try:
            del (self.ptxt)
        except Exception as err:
            self.fail("PyPtxt() deletion failed unexpectedly: ", err)

    def test_PyCtxt_creation_deletion(self):
        try:
            self.ctxt = PyCtxt()
            self.ctxt2 = PyCtxt(other_ctxt=self.ctxt)
            self.pyfhel = Pyfhel()
            self.ctxt3 = PyCtxt(pyfhel=self.pyfhel)
            self.ctxt4 = PyCtxt(other_ctxt=self.ctxt3)
        except Exception as err:
            self.fail("PyCtxt() creation failed unexpectedly: ", err)
        self.assertEqual(self.ctxt.size(), 2)
        self.assertEqual(self.ctxt._encoding, ENCODING_t.UNDEFINED)
        self.ctxt._encoding = ENCODING_t.FRACTIONAL
        self.assertEqual(self.ctxt._encoding, ENCODING_t.FRACTIONAL)
        del (self.ctxt._encoding)
        self.assertEqual(self.ctxt._encoding, ENCODING_t.UNDEFINED)
        self.assertEqual(self.ctxt.size(), 2)
        self.ctxt._pyfhel = self.pyfhel
        self.ctxt2._pyfhel = self.ctxt._pyfhel
        try:
            del (self.ctxt)
        except Exception as err:
            self.fail("PyCtxt() deletion failed unexpectedly: ", err)

    def test_Pyfhel_1_GENERATION(self):
        pass

    def test_Pyfhel_1a_creation_deletion(self):
        try:
            self.pyfhel = Pyfhel()
        except Exception as err:
            self.fail("Pyfhel() creation failed unexpectedly: ", err)
        try:
            del (self.pyfhel)
        except Exception as err:
            self.fail("Pyfhel() deletion failed unexpectedly: ", err)

    def test_Pyfhel_1b_context_n_key_generation(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(65537)
        self.pyfhel.keyGen()

    def test_Pyfhel_1c_rotate_key_generation(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(65537)
        self.pyfhel.keyGen()
        self.pyfhel.rotateKeyGen(30)
        self.pyfhel.rotateKeyGen(1)
        self.pyfhel.rotateKeyGen(60)
        self.assertRaises(SystemError, lambda: self.pyfhel.rotateKeyGen(61))
        self.assertRaises(SystemError, lambda: self.pyfhel.rotateKeyGen(0))

    def test_Pyfhel_1d_relin_key_generation(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(65537)
        self.pyfhel.keyGen()
        self.pyfhel.relinKeyGen(30, 5)
        self.pyfhel.relinKeyGen(1, 5)
        self.pyfhel.relinKeyGen(60, 5)
        self.assertRaises(SystemError, lambda: self.pyfhel.relinKeyGen(61, 5))
        self.assertRaises(SystemError, lambda: self.pyfhel.relinKeyGen(0, 5))

    def test_Pyfhel_2_ENCODING(self):
        pass

    def test_Pyfhel_2a_encode_decode_int(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(p=65537)
        self.pyfhel.keyGen()
        self.ptxt = self.pyfhel.encodeInt(127)
        self.assertEqual(self.ptxt.to_string(),
                         b'1x^6 + 1x^5 + 1x^4 + 1x^3 + 1x^2 + 1x^1 + 1')
        self.assertEqual(self.pyfhel.decodeInt(self.ptxt), 127)
        self.ptxt2 = PyPtxt(self.ptxt)
        self.pyfhel.encodeInt(-2, self.ptxt)
        self.assertEqual(self.ptxt.to_string(), b'10000x^1')
        self.assertEqual(self.pyfhel.decodeInt(self.ptxt), -2)
        self.assertEqual(self.pyfhel.decodeInt(self.ptxt2), 127)

    def test_Pyfhel_2b_encode_decode_float(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(p=65537,
                               m=8192,
                               base=2,
                               intDigits=80,
                               fracDigits=20)
        self.pyfhel.keyGen()
        self.ptxt = self.pyfhel.encodeFrac(19.30)
        self.assertTrue(self.ptxt.to_string(), b'9x^8190 + 1x^4 + 1x^1 + 1')
        self.assertEqual(round(self.pyfhel.decodeFrac(self.ptxt), 2), 19.30)
        self.pyfhel.encodeFrac(-2.25, self.ptxt)
        self.assertEqual(self.ptxt.to_string(), b'1x^8190 + 10000x^1')
        self.assertEqual(round(self.pyfhel.decodeFrac(self.ptxt), 2), -2.25)

    def test_Pyfhel_2c_encode_decode_batch(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(p=1964769281,
                               m=8192,
                               base=2,
                               sec=192,
                               flagBatching=True)
        self.pyfhel.keyGen()
        self.assertTrue(self.pyfhel.batchEnabled())
        self.ptxt = self.pyfhel.encodeBatch([1, 2, 3, 4, 5, 6])
        self.assertEqual(self.pyfhel.getnSlots(), 8192)
        self.assertEqual(
            self.pyfhel.decodeBatch(self.ptxt)[:6], [1, 2, 3, 4, 5, 6])

        #print(self.ptxt.to_string())

    def test_Pyfhel_2d_encode_decode_array(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(p=1964769281,
                               m=8192,
                               base=2,
                               sec=192,
                               flagBatching=True)
        self.pyfhel.keyGen()
        self.assertTrue(self.pyfhel.batchEnabled())
        self.ptxt = self.pyfhel.encodeArray(np.array([1, 2, 3, 4, 5, 6]))
        self.assertEqual(self.pyfhel.getnSlots(), 8192)
        self.assertTrue(
            np.alltrue(
                self.pyfhel.decodeArray(self.ptxt)[:6] == np.array(
                    [1, 2, 3, 4, 5, 6])))

    def test_Pyfhel_3_ENCRYPTING(self):
        pass

    def test_Pyfhel_3a_encrypt_decrypt_int(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(p=65537)
        self.pyfhel.keyGen()
        self.ctxt = self.pyfhel.encryptInt(127)
        self.assertEqual(self.pyfhel.decryptInt(self.ctxt), 127)
        self.ctxt2 = PyCtxt(self.ctxt)
        self.pyfhel.encryptInt(-2, self.ctxt)
        self.assertEqual(self.pyfhel.decryptInt(self.ctxt), -2)
        self.assertEqual(self.pyfhel.decryptInt(self.ctxt), -2)
        self.assertEqual(self.pyfhel.decryptInt(self.ctxt2), 127)

    def test_Pyfhel_3b_encrypt_decrypt_float(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(p=65537,
                               m=8192,
                               base=2,
                               intDigits=80,
                               fracDigits=20)
        self.pyfhel.keyGen()
        self.ctxt = self.pyfhel.encryptFrac(19.30)
        self.assertEqual(round(self.pyfhel.decryptFrac(self.ctxt), 2), 19.30)
        self.pyfhel.encryptFrac(-2.25, self.ctxt)
        self.assertEqual(round(self.pyfhel.decryptFrac(self.ctxt), 2), -2.25)

    def test_Pyfhel_3c_encrypt_decrypt_batch(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(p=1964769281,
                               m=8192,
                               base=2,
                               sec=192,
                               flagBatching=True)
        self.pyfhel.keyGen()
        self.assertTrue(self.pyfhel.batchEnabled())
        self.ctxt = self.pyfhel.encryptBatch([1, 2, 3, 4, 5, 6])
        self.assertEqual(self.pyfhel.getnSlots(), 8192)
        self.assertEqual(
            self.pyfhel.decryptBatch(self.ctxt)[:6], [1, 2, 3, 4, 5, 6])

        #print(self.ptxt.to_string())

    def test_Pyfhel_3d_encrypt_decrypt_array(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(p=1964769281,
                               m=8192,
                               base=2,
                               sec=192,
                               flagBatching=True)
        self.pyfhel.keyGen()
        self.assertTrue(self.pyfhel.batchEnabled())
        self.ctxt = self.pyfhel.encryptArray(np.array([1, 2, 3, 4, 5, 6]))
        self.assertEqual(self.pyfhel.getnSlots(), 8192)
        self.assertTrue(
            np.alltrue(
                self.pyfhel.decryptArray(self.ctxt)[:6] == np.array(
                    [1, 2, 3, 4, 5, 6])))

    def test_Pyfhel_4_OPERATIONS(self):
        pass

    def test_Pyfhel_4a_operations_integer(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(p=1964769281, m=8192, base=3, sec=192)
        self.pyfhel.keyGen()
        #self.pyfhel.rotateKeyGen(60)
        #self.pyfhel.relinKeyGen(60)

        self.ctxti = self.pyfhel.encryptInt(127)
        self.ctxti2 = self.pyfhel.encryptInt(-2)
        self.ptxti = self.pyfhel.encodeInt(3)

        self.ctxt_add = self.pyfhel.add(self.ctxti,
                                        self.ctxti2,
                                        in_new_ctxt=True)
        self.ctxt_add2 = self.pyfhel.add_plain(self.ctxti,
                                               self.ptxti,
                                               in_new_ctxt=True)
        self.ctxt_sub = self.pyfhel.sub(self.ctxti,
                                        self.ctxti2,
                                        in_new_ctxt=True)
        self.ctxt_sub2 = self.pyfhel.sub_plain(self.ctxti,
                                               self.ptxti,
                                               in_new_ctxt=True)
        self.ctxt_mult = self.pyfhel.multiply(self.ctxti,
                                              self.ctxti2,
                                              in_new_ctxt=True)
        self.ctxt_mult2 = self.pyfhel.multiply_plain(self.ctxti,
                                                     self.ptxti,
                                                     in_new_ctxt=True)
        #self.ctxt_rotate = self.pyfhel.rotate(self.ctxti, 2)
        #self.ctxt_expon = self.pyfhel.power(self.ctxti, 3)
        #self.ctxt_expon2 = self.pyfhel.power(self.ctxti2, 3)
        #self.ctxt_polyEval = self.pyfhel.polyEval(self.ctxti, [1, 2, 1], in_new_ctxt=True)

        self.assertEqual(self.pyfhel.decryptInt(self.ctxt_add), 125)
        self.assertEqual(self.pyfhel.decryptInt(self.ctxt_add2), 130)
        self.assertEqual(self.pyfhel.decryptInt(self.ctxt_sub), 129)
        self.assertEqual(self.pyfhel.decryptInt(self.ctxt_sub2), 124)
        self.assertEqual(self.pyfhel.decryptInt(self.ctxt_mult), -254)
        self.assertEqual(self.pyfhel.decryptInt(self.ctxt_mult2), 381)
        #self.assertEqual(self.pyfhel.decryptInt(self.ctxt_expon), 2048383)
        #self.assertEqual(self.pyfhel.decryptInt(self.ctxt_expon2), -8)
        #self.assertEqual(self.pyfhel.decryptInt(self.ctxt_polyEval), 16510)

    def test_Pyfhel_4b_operations_frac(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(p=1964769281, m=8192, base=3, sec=192)
        self.pyfhel.keyGen()
        #self.pyfhel.rotateKeyGen(60)
        #self.pyfhel.relinKeyGen(60)

        self.ctxti = self.pyfhel.encryptFrac(19.37)
        self.ctxti2 = self.pyfhel.encryptFrac(-2.25)
        self.ptxti = self.pyfhel.encodeFrac(3.12)

        self.ctxt_add = self.pyfhel.add(self.ctxti,
                                        self.ctxti2,
                                        in_new_ctxt=True)
        self.ctxt_add2 = self.pyfhel.add_plain(self.ctxti,
                                               self.ptxti,
                                               in_new_ctxt=True)
        self.ctxt_sub = self.pyfhel.sub(self.ctxti,
                                        self.ctxti2,
                                        in_new_ctxt=True)
        self.ctxt_sub2 = self.pyfhel.sub_plain(self.ctxti,
                                               self.ptxti,
                                               in_new_ctxt=True)
        self.ctxt_mult = self.pyfhel.multiply(self.ctxti,
                                              self.ctxti2,
                                              in_new_ctxt=True)
        self.ctxt_mult2 = self.pyfhel.multiply_plain(self.ctxti,
                                                     self.ptxti,
                                                     in_new_ctxt=True)

        self.assertEqual(round(self.pyfhel.decryptFrac(self.ctxt_add), 2),
                         17.12)
        self.assertEqual(round(self.pyfhel.decryptFrac(self.ctxt_add2), 2),
                         22.49)
        self.assertEqual(round(self.pyfhel.decryptFrac(self.ctxt_sub), 2),
                         21.62)
        self.assertEqual(round(self.pyfhel.decryptFrac(self.ctxt_sub2), 2),
                         16.25)
        self.assertEqual(round(self.pyfhel.decryptFrac(self.ctxt_mult), 2),
                         -43.58)
        self.assertEqual(round(self.pyfhel.decryptFrac(self.ctxt_mult2), 2),
                         60.43)

    def test_Pyfhel_4c_operations_batch_array(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(p=1964769281,
                               m=8192,
                               base=2,
                               sec=192,
                               flagBatching=True)
        self.pyfhel.keyGen()
        self.pyfhel.rotateKeyGen(60)
        self.ctxti = self.pyfhel.encryptBatch([1, 2, 3, 4, 5, 6])
        self.ctxti2 = self.pyfhel.encryptArray(
            np.array([-6, -5, -4, -3, -2, -1]))
        self.ptxti = self.pyfhel.encodeArray(np.array([12, 15, 18, 21, 24,
                                                       27]))

        self.ctxt_add = self.pyfhel.add(self.ctxti,
                                        self.ctxti2,
                                        in_new_ctxt=True)
        self.ctxt_add2 = self.pyfhel.add_plain(self.ctxti,
                                               self.ptxti,
                                               in_new_ctxt=True)
        self.ctxt_sub = self.pyfhel.sub(self.ctxti,
                                        self.ctxti2,
                                        in_new_ctxt=True)
        self.ctxt_sub2 = self.pyfhel.sub_plain(self.ctxti,
                                               self.ptxti,
                                               in_new_ctxt=True)
        self.ctxt_mult = self.pyfhel.multiply(self.ctxti,
                                              self.ctxti2,
                                              in_new_ctxt=True)
        self.ctxt_mult2 = self.pyfhel.multiply_plain(self.ctxti,
                                                     self.ptxti,
                                                     in_new_ctxt=True)
        self.ctxt_rotate = self.pyfhel.rotate(self.ctxti, -2, in_new_ctxt=True)
        self.ctxt_rotate2 = self.pyfhel.rotate(self.ctxti, 2, in_new_ctxt=True)
        #self.ctxt_expon = self.pyfhel.power(self.ctxti, 3)
        #self.ctxt_expon2 = self.pyfhel.power(self.ctxti2, 3)
        #self.ctxt_polyEval = self.pyfhel.polyEval(self.ctxti, [1, 2, 1], in_new_ctxt=True)

        self.assertEqual(
            self.pyfhel.decryptBatch(self.ctxt_add)[:6], [-5, -3, -1, 1, 3, 5])
        self.assertEqual(
            self.pyfhel.decryptBatch(self.ctxt_add2)[:6],
            [13, 17, 21, 25, 29, 33])
        self.assertEqual(
            self.pyfhel.decryptBatch(self.ctxt_sub)[:6], [7, 7, 7, 7, 7, 7])
        self.assertEqual(
            self.pyfhel.decryptBatch(self.ctxt_sub2)[:6],
            [-11, -13, -15, -17, -19, -21])
        self.assertEqual(
            self.pyfhel.decryptBatch(self.ctxt_mult)[:6],
            [-6, -10, -12, -12, -10, -6])
        self.assertEqual(
            self.pyfhel.decryptBatch(self.ctxt_mult2)[:6],
            [12, 30, 54, 84, 120, 162])
        self.assertEqual(
            self.pyfhel.decryptBatch(self.ctxt_rotate)[:6], [0, 0, 1, 2, 3, 4])
        self.assertEqual(
            self.pyfhel.decryptBatch(self.ctxt_rotate2)[:6],
            [3, 4, 5, 6, 0, 0])

    def test_Pyfhel_5_IO_SAVE_RESTORE(self):
        pass

    def test_Pyfhel_5a_save_objects(self):
        self.pyfhel = Pyfhel()
        self.pyfhel.contextGen(p=1964769281,
                               m=8192,
                               base=2,
                               sec=192,
                               flagBatching=True)
        self.pyfhel.keyGen()
        self.pyfhel.rotateKeyGen(60)
        #self.pyfhel.relinKeyGen(60)

        self.assertTrue(self.pyfhel.saveContext(b"context.pycon"))
        self.assertTrue(self.pyfhel.savepublicKey(b"public_k.pypk"))
        self.assertTrue(self.pyfhel.savesecretKey(b"secret_k.pysk"))
        #self.assertTrue(self.pyfhel.saverelinKey(b"relin_k.pyrlk"))
        self.assertTrue(self.pyfhel.saverotateKey(b"rotate_k.pyrok"))

    def test_Pyfhel_5b_restore_objects(self):
        self.pyfhel = Pyfhel()
        self.assertTrue(self.pyfhel.restoreContext(b"context.pycon"))
        self.assertTrue(self.pyfhel.restoresecretKey(b"secret_k.pysk"))
        self.assertTrue(self.pyfhel.restorepublicKey(b"public_k.pypk"))
        #self.assertTrue(self.pyfhel.restorerelinKey(b"relin_k.pyrlk"))
        self.assertTrue(self.pyfhel.restorerotateKey(b"rotate_k.pyrok"))
        os.remove(b"context.pycon")
        os.remove(b"secret_k.pysk")
        os.remove(b"public_k.pypk")
        os.remove(b"rotate_k.pyrok")
コード例 #15
0
ファイル: Demo_SaveNRestore.py プロジェクト: fabyulshi/Pyfhel
HE.savepublicKey(tmp_dir.name + "/pub.key")
HE.savesecretKey(tmp_dir.name + "/sec.key")
HE.saverelinKey(tmp_dir.name + "/relin.key")
HE.saverotateKey(tmp_dir.name + "/rotate.key")

print("3. Restore all keys")
HE2 = Pyfhel()
HE2.restoreContext(tmp_dir.name + "/context")
HE2.restorepublicKey(tmp_dir.name + "/pub.key")
HE2.restoresecretKey(tmp_dir.name + "/sec.key")
HE2.restorerelinKey(tmp_dir.name + "/relin.key")
HE2.restorerotateKey(tmp_dir.name + "/rotate.key")

print("4. Testing encryption decryption:")
ctxt1 = HE.encryptBatch([42])
assert HE2.decryptBatch(
    ctxt1)[0] == 42, "decrypting with restored keys should work"
HE2.rotate(ctxt1, -1)
assert HE2.decryptBatch(
    ctxt1)[1] == 42, "decrypting with restored keys should work"

print("5. Testing ciphertext storing:")
ctxt2 = HE.encryptInt(42)
ctxt2.save(tmp_dir.name + "/ctxt2")

ctxt_restored = PyCtxt()
ctxt_restored.load(tmp_dir.name + "/ctxt2", int)
assert HE2.decryptInt(ctxt_restored) == 42, "decrypting ciphertext should work"

# Cleaning up secure channel
tmp_dir.cleanup()
コード例 #16
0
print("\n\t".join(os.listdir(tmp_dir_name)))

# Now we restore everything and quickly check if it works. 
#  Note! make sure to set the `pyfhel` parameter in PyCtxt/PyPtxt creation!
HE_f = Pyfhel() # Empty creation
HE_f.load_context(tmp_dir_name + "/context")
HE_f.load_public_key(tmp_dir_name + "/pub.key")
HE_f.load_secret_key(tmp_dir_name + "/sec.key")
HE_f.load_relin_key(tmp_dir_name + "/relin.key")
HE_f.load_rotate_key(tmp_dir_name + "/rotate.key")
c_f = PyCtxt(pyfhel=HE_f, fileName=tmp_dir_name + "/c.ctxt")
p_f = PyPtxt(pyfhel=HE_f, fileName=tmp_dir_name + "/p.ptxt", scheme='bfv')

print("2b. Loading everything from files into a new environment.")
# Some checks
assert HE_f.decryptInt(HE_f.encryptInt(np.array([42])))[0]==42, "Incorrect encryption"
assert HE_f.decryptInt(c_f)[0]==42, "Incorrect decryption/ciphertext"
assert HE_f.decodeInt(p_f)[0]==-1, "Incorrect decoding"
assert HE_f.decryptInt(c_f >> 1)[1]==42, "Incorrect Rotation"
c_relin = c_f**2
~c_relin
assert c_relin.size()==2, "Incorrect relinearization"
print(" All checks passed! Loaded from files correctly")
# Cleaning up temporary directory
tmp_dir.cleanup()


# %%
# 3. Save everything into byte-strings
# ----------------------------------------
# Now we save all objects into bytestrings