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

        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)
        ctxt_rotate = pyfhel.rotate(ctxti, -2, in_new_ctxt=True)
        ctxt_rotate2 = pyfhel.rotate(ctxti, 2, in_new_ctxt=True)

        self.assertEqual(pyfhel.decryptBatch(ctxt_add)[:6], [-5, -3, -1, 1, 3, 5])
        self.assertEqual(pyfhel.decryptBatch(ctxt_add2)[:6], [13, 17, 21, 25, 29, 33])
        self.assertEqual(pyfhel.decryptBatch(ctxt_sub)[:6], [7, 7, 7, 7, 7, 7])
        self.assertEqual(
            pyfhel.decryptBatch(ctxt_sub2)[:6], [-11, -13, -15, -17, -19, -21]
        )
        self.assertEqual(
            pyfhel.decryptBatch(ctxt_mult)[:6], [-6, -10, -12, -12, -10, -6]
        )
        self.assertEqual(
            pyfhel.decryptBatch(ctxt_mult2)[:6], [12, 30, 54, 84, 120, 162]
        )
        self.assertEqual(pyfhel.decryptBatch(ctxt_rotate)[:6], [0, 0, 1, 2, 3, 4])
        self.assertEqual(pyfhel.decryptBatch(ctxt_rotate2)[:6], [3, 4, 5, 6, 0, 0])
Exemple #2
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)
Exemple #3
0
    def HE(self):
        HE = Pyfhel()
        HE.contextGen(m=2048, p=65537)
        HE.keyGen()
        HE.relinKeyGen(60, 3)

        return HE
Exemple #4
0
    def test_call(self):
        HE = Pyfhel()
        HE.contextGen(65537)
        HE.keyGen()
        HE.relinKeyGen(30, 100)

        new_weights = np.array([
            [1, 2, 3, 4]
           ,[2, 3, 4, 5]
           ,[3, 4, 5, 6]
        ])
        new_bias = np.array([1, 2, 3])

        linear_layer = lin.LinearLayer(HE, new_weights, new_bias)

        flattened_input = np.array([
            [1, 2, 3, 4]
            , [5, 6, 7, 8]
        ])
        encrypted_input = cr.encrypt_matrix(HE, flattened_input)

        encrypted_result = linear_layer(encrypted_input)
        result = cr.decrypt_matrix(HE, encrypted_result)

        expected_result = np.array([
            [31, 42, 53]
            ,[71, 98, 125]
        ])
        assert np.allclose(result, expected_result)
Exemple #5
0
 def test_Pyfhel_3b_encrypt_decrypt_float(self):
     pyfhel = Pyfhel()
     pyfhel.contextGen(p=65537, m=8192, base=2, intDigits=80, fracDigits=20)
     pyfhel.keyGen()
     ctxt = pyfhel.encryptFrac(19.30)
     self.assertEqual(round(pyfhel.decryptFrac(ctxt), 2), 19.30)
     pyfhel.encryptFrac(-2.25, ctxt)
     self.assertEqual(round(pyfhel.decryptFrac(ctxt), 2), -2.25)
Exemple #6
0
 def test_Pyfhel_3c_encrypt_decrypt_batch(self):
     pyfhel = Pyfhel()
     pyfhel.contextGen(p=1964769281, m=8192, base=2, sec=192, flagBatching=True)
     pyfhel.keyGen()
     self.assertTrue(pyfhel.batchEnabled())
     ctxt = pyfhel.encryptBatch([1, 2, 3, 4, 5, 6])
     self.assertEqual(pyfhel.getnSlots(), 8192)
     self.assertEqual(pyfhel.decryptBatch(ctxt)[:6], [1, 2, 3, 4, 5, 6])
Exemple #7
0
 def test_Pyfhel_1c_rotate_key_generation(self):
     pyfhel = Pyfhel()
     pyfhel.contextGen(65537)
     pyfhel.keyGen()
     pyfhel.rotateKeyGen(30)
     pyfhel.rotateKeyGen(1)
     pyfhel.rotateKeyGen(60)
     self.assertRaises(SystemError, lambda: pyfhel.rotateKeyGen(61))
     self.assertRaises(SystemError, lambda: pyfhel.rotateKeyGen(0))
Exemple #8
0
 def test_Pyfhel_1d_relin_key_generation(self):
     pyfhel = Pyfhel()
     pyfhel.contextGen(65537)
     pyfhel.keyGen()
     pyfhel.relinKeyGen(30, 5)
     pyfhel.relinKeyGen(1, 5)
     pyfhel.relinKeyGen(60, 5)
     self.assertRaises(SystemError, lambda: pyfhel.relinKeyGen(61, 5))
     self.assertRaises(SystemError, lambda: pyfhel.relinKeyGen(0, 5))
Exemple #9
0
    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()
Exemple #10
0
 def test_Pyfhel_3d_encrypt_decrypt_array(self):
     pyfhel = Pyfhel()
     pyfhel.contextGen(p=1964769281, m=8192, base=2, sec=192, flagBatching=True)
     pyfhel.keyGen()
     self.assertTrue(pyfhel.batchEnabled())
     ctxt = pyfhel.encryptArray(np.array([1, 2, 3, 4, 5, 6], dtype=np.int64))
     self.assertEqual(pyfhel.getnSlots(), 8192)
     self.assertTrue(
         np.alltrue(pyfhel.decryptArray(ctxt)[:6] == np.array([1, 2, 3, 4, 5, 6], dtype=np.int64))
     )
Exemple #11
0
 def test_Pyfhel_2d_encode_decode_array(self):
     pyfhel = Pyfhel()
     pyfhel.contextGen(p=1964769281, m=8192, base=2, sec=192, flagBatching=True)
     pyfhel.keyGen()
     self.assertTrue(pyfhel.batchEnabled())
     ptxt = pyfhel.encodeArray(np.array([1, 2, 3, 4, 5, 6]))
     self.assertEqual(pyfhel.getnSlots(), 8192)
     self.assertTrue(
         np.alltrue(pyfhel.decodeArray(ptxt)[:6] == np.array([1, 2, 3, 4, 5, 6]))
     )
Exemple #12
0
 def test_Pyfhel_2b_encode_decode_float(self):
     pyfhel = Pyfhel()
     pyfhel.contextGen(p=65537, m=8192, base=2, intDigits=80, fracDigits=20)
     pyfhel.keyGen()
     ptxt = pyfhel.encodeFrac(19.30)
     self.assertTrue(ptxt.to_poly_string(), b"9x^8190 + 1x^4 + 1x^1 + 1")
     self.assertEqual(round(pyfhel.decodeFrac(ptxt), 2), 19.30)
     pyfhel.encodeFrac(-2.25, ptxt)
     self.assertEqual(ptxt.to_poly_string(), b"1x^8190 + 10000x^1")
     self.assertEqual(round(pyfhel.decodeFrac(ptxt), 2), -2.25)
Exemple #13
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)
Exemple #14
0
    def test_Pyfhel_5a_save_objects(self):
        pyfhel = Pyfhel()
        pyfhel.contextGen(p=1964769281, m=8192, base=2, sec=192, flagBatching=True)
        pyfhel.keyGen()
        pyfhel.rotateKeyGen(60)
        pyfhel.relinKeyGen(60,3)

        self.assertTrue(pyfhel.saveContext("context.pycon"))
        self.assertTrue(pyfhel.savepublicKey("public_k.pypk"))
        self.assertTrue(pyfhel.savesecretKey("secret_k.pysk"))
        self.assertTrue(pyfhel.saverelinKey("relin_k.pyrlk"))
        self.assertTrue(pyfhel.saverotateKey("rotate_k.pyrok"))
Exemple #15
0
    def test_get_min_noise(self):

        HE = Pyfhel()
        HE.contextGen(65537)
        HE.keyGen()
        plain_image = np.array([[[1, 2, 3], [1, 3, 4], [1, 3, 4]]])

        cipher_image = encrypt_matrix(HE, plain_image)
        cipher_image[0][1][1] = cipher_image[0][1][1] * HE.encryptFrac(2)

        assert get_min_noise(HE, cipher_image) == HE.noiseLevel(
            cipher_image[0][1][1])
Exemple #16
0
 def test_Pyfhel_2a_encode_decode_int(self):
     pyfhel = Pyfhel()
     pyfhel.contextGen(p=65537)
     pyfhel.keyGen()
     ptxt = pyfhel.encodeInt(127)
     self.assertEqual(ptxt.to_poly_string(),
                      b"1x^6 + 1x^5 + 1x^4 + 1x^3 + 1x^2 + 1x^1 + 1")
     self.assertEqual(pyfhel.decodeInt(ptxt), 127)
     ptxt2 = PyPtxt(ptxt)
     pyfhel.encodeInt(-2, ptxt)
     self.assertEqual(ptxt.to_poly_string(), b"10000x^1")
     self.assertEqual(pyfhel.decodeInt(ptxt), -2)
     self.assertEqual(pyfhel.decodeInt(ptxt2), 127)
Exemple #17
0
    def test_init(self):
        HE = Pyfhel()
        HE.contextGen(65537)
        HE.keyGen()
        HE.relinKeyGen(30, 100)

        new_weights = np.array([
            [1, 2, 3, 4]
           ,[2, 3, 4, 5]
           ,[3, 4, 5, 6]
        ])

        linear_layer = lin.LinearLayer(HE, new_weights)

        assert HE.decodeFrac(linear_layer.weights[0][0]) == 1
        assert HE.decodeFrac(linear_layer.weights[0][1]) == 2
        assert HE.decodeFrac(linear_layer.weights[0][2]) == 3
        assert HE.decodeFrac(linear_layer.weights[0][3]) == 4
        assert HE.decodeFrac(linear_layer.weights[1][0]) == 2
        assert HE.decodeFrac(linear_layer.weights[1][1]) == 3
        assert HE.decodeFrac(linear_layer.weights[1][2]) == 4
        assert HE.decodeFrac(linear_layer.weights[1][3]) == 5
        assert HE.decodeFrac(linear_layer.weights[2][0]) == 3
        assert HE.decodeFrac(linear_layer.weights[2][1]) == 4
        assert HE.decodeFrac(linear_layer.weights[2][2]) == 5
        assert HE.decodeFrac(linear_layer.weights[2][3]) == 6

        assert linear_layer.bias == None

        bias = np.array([2, 2, 2])

        linear_layer2 = lin.LinearLayer(HE, new_weights, bias)

        assert HE.decodeFrac(linear_layer.weights[0][0]) == 1
        assert HE.decodeFrac(linear_layer.weights[0][1]) == 2
        assert HE.decodeFrac(linear_layer.weights[0][2]) == 3
        assert HE.decodeFrac(linear_layer.weights[0][3]) == 4
        assert HE.decodeFrac(linear_layer.weights[1][0]) == 2
        assert HE.decodeFrac(linear_layer.weights[1][1]) == 3
        assert HE.decodeFrac(linear_layer.weights[1][2]) == 4
        assert HE.decodeFrac(linear_layer.weights[1][3]) == 5
        assert HE.decodeFrac(linear_layer.weights[2][0]) == 3
        assert HE.decodeFrac(linear_layer.weights[2][1]) == 4
        assert HE.decodeFrac(linear_layer.weights[2][2]) == 5
        assert HE.decodeFrac(linear_layer.weights[2][3]) == 6

        assert HE.decodeFrac(linear_layer2.bias[0]) == 2
        assert HE.decodeFrac(linear_layer2.bias[1]) == 2
        assert HE.decodeFrac(linear_layer2.bias[2]) == 2
Exemple #18
0
    def test_get_max_error(self):

        HE = Pyfhel()
        HE.contextGen(65537)
        HE.keyGen()
        plain_image = np.array([[1, 2, 3], [1, 3, 4], [1, 3, 4]])

        cipher_image = encrypt_matrix(HE, plain_image)

        cipher_image[2][0] = HE.encryptFrac(-1)

        max_error, position = get_max_error(HE, plain_image, cipher_image)

        assert max_error == 2
        assert position, (2 == 0)
Exemple #19
0
 def test_Pyfhel_5d_save_restore_batch(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.encryptBatch([1, 2, 3, 4])
     # save to temporary file
     tmp = tempfile.NamedTemporaryFile()
     ctxt.save(tmp.name)
     # load from temporary file
     loaded = PyCtxt()
     loaded.load(tmp.name, "batch")
     self.assertEqual(pyfhel.decryptBatch(loaded)[:4], [1, 2, 3, 4])
Exemple #20
0
def encryptImg(Img):
    Img_shape = Img.shape
    print(Img_shape)
    encImg = [[0 for j in range(Img_shape[1])] for i in range(Img_shape[0])]
    pyfhel = Pyfhel()  # Creating empty Pyfhel object
    pyfhel.contextGen(p=65537, m=1024,
                      flagBatching=True)  # Generating context. (encrypt pixel)
    pyfhel.keyGen()  # keygeneration

    for py in range(Img_shape[0]):
        for px in range(Img_shape[1]):
            temp_pxl = Img[py, px]

            cxt_pxl = pyfhel.encryptFrac(temp_pxl)  # test floating number
            dec_pxl = pyfhel.decryptFrac(cxt_pxl)  # decrypt
            encImg[py][px] = cxt_pxl
    return encImg, pyfhel
Exemple #21
0
 def test_Pyfhel_5f_save_restore_batch(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.encryptBatch([1, 2, 3, 4])
     # 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, "batch")
     self.assertEqual(pyfhel.decryptBatch(loaded)[:4], [1, 2, 3, 4])
     tmp_dir.cleanup()
Exemple #22
0
class customer():
    def __init__(self, p):
        self.HE = Pyfhel()
        self.HE.contextGen(p=p)
        self.HE.keyGen()

    def save(self, context_path, pk_path, sk_path):
        self.HE.saveContext(context_path)
        self.HE.savepublicKey(pk_path)
        self.HE.savesecretKey(sk_path)

    def ecnypt(self, arr):
        '''
        :param arr: should be float numpy matrix
        :return: encrypted numpy matrix
        '''
        row, col = arr.shape[0], arr.shape[1]
        new_a = []
        for i in range(row):
            row_val = []
            for j in range(col):
                row_val.append(self.HE.encryptFrac(arr[i, j]))
            new_a.append(row_val)
        new_a = np.asarray(new_a)
        return new_a.reshape(row, col)

    def decrypt(self, enc_arr):
        '''
        :param enc_arr: encrypted numpy matrix
        :return: float numpy matrix
        '''
        row, col = enc_arr.shape[0], enc_arr.shape[1]
        new_a = []
        for i in range(row):
            row_val = []
            for j in range(col):
                row_val.append(self.HE.decryptFrac(enc_arr[i, j]))
            new_a.append(row_val)
        new_a = np.asarray(new_a)
        return new_a.reshape(row, col)

    def decrypt_scalar(self, enc_scalar):
        return self.HE.decryptFrac(enc_scalar)
Exemple #23
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')
Exemple #24
0
    def test_Pyfhel_4b_operations_frac(self):
        pyfhel = Pyfhel()
        pyfhel.contextGen(p=1964769281, m=8192, base=3, sec=192)
        pyfhel.keyGen()

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

        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(round(pyfhel.decryptFrac(ctxt_add), 2), 17.12)
        self.assertEqual(round(pyfhel.decryptFrac(ctxt_add2), 2), 22.49)
        self.assertEqual(round(pyfhel.decryptFrac(ctxt_sub), 2), 21.62)
        self.assertEqual(round(pyfhel.decryptFrac(ctxt_sub2), 2), 16.25)
        self.assertEqual(round(pyfhel.decryptFrac(ctxt_mult), 2), -43.58)
        self.assertEqual(round(pyfhel.decryptFrac(ctxt_mult2), 2), 60.43)
Exemple #25
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)
Exemple #26
0
import time

from Pyfhel import Pyfhel, PyPtxt, PyCtxt
# Pyfhel class contains most of the functions.
# PyPtxt is the plaintext class
# PyCtxt is the ciphertext class

print("==============================================================")
print("================== Pyfhel CONTEXT PARAMETERS =================")
print("==============================================================")

print("1. p (long): Plaintext modulus. All operations are modulo p. ")
HE = Pyfhel()  # Creating empty Pyfhel object
HE.contextGen(p=65537)  # Generating context. The value of p is important.
#  There are many configurable parameters on this step
HE.keyGen()  # Key Generation.

print("2. m (long=2048): Polynomial coefficient modulus.")
print(
    "   Higher allows more encrypted operations. In batch mode it is the number of integers per ciphertext."
)


def time_demo_helloworld(integer1=127, integer2=-2):
    start = time.time()
    ctxt1 = HE.encryptInt(integer1)  # Encryption makes use of the public key
    ctxt2 = HE.encryptInt(
        integer2)  # For integers, encryptInt function is used.
    ctxtSum = ctxt1 + ctxt2  # `ctxt1 += ctxt2` for quicker inplace operation
    ctxtSub = ctxt1 - ctxt2  # `ctxt1 -= ctxt2` for quicker inplace operation
    ctxtMul = ctxt1 * ctxt2  # `ctxt1 *= ctxt2` for quicker inplace operation
Exemple #27
0
from Pyfhel import Pyfhel,PyCtxt,PyPtxt
import numpy as np
import time
he=Pyfhel()
he.contextGen(p=1179649,m=32768,flagBatching=True,fracDigits=20)
he.keyGen()
a=PyCtxt()
b=PyCtxt()
q=0
cc=0

#加密文件
def PPctxt(name):
  fil=open(name)
  lines=fil.readlines()
  strr=''.join(lines)
  global l
  l=len(strr)
  l=l-1
  arr=[]
  for line in strr:
      for ind in line:
          arr.append(ind)
  #arr.remove('\n')
  brr=[]
  for i in arr:
      brr.append(ord(i))
  crr=np.array(brr)
  #列表数据转数组  
  err=he.encryptBatch(crr)
  err.save(name)
Exemple #28
0
# * PyPtxt is the plaintext class
# * PyCtxt is the ciphertext class
import numpy as np
from Pyfhel import Pyfhel
print("1. Import Pyfhel class, and numpy for the inputs to encrypt.")
# %%
# 2. Context and key setup
# ---------------------------
# We will start the Helloworld by generating a context and a public/secret key pair.
# This is all managed by a Pyfhel instance under the hood.
HE = Pyfhel()           # Creating empty Pyfhel object
HE.contextGen(scheme='bfv', n=2**14, t_bits=20)  # Generate context for 'bfv'/'ckks' scheme
                        # 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))
Exemple #29
0
def remote_execution_aws(data, parameters):
    def encode_ciphertext(c, temp_file):
        with (open(temp_file.name, "w+b")) as f:
            c.save(temp_file.name)
            bc = f.read()
            b64 = str(base64.b64encode(bc))[2:-1]
            return b64

    def decode_ciphertext(b64, temp_file):
        with (open(temp_file.name, "w+b")) as f:
            x = bytes(b64, encoding='utf-8')
            x = base64.decodebytes(x)
            f.write(x)
            c = HE.encryptFrac(0)
            c.load(temp_file.name, "float")
            return c

    def crypt_and_encode(HE, t, ret_dict, ind):
        temp_file = tempfile.NamedTemporaryFile()
        enc_image = encrypt_matrix(HE, t)

        data = [[[[encode_ciphertext(value, temp_file) for value in row]
                  for row in column] for column in layer]
                for layer in enc_image]
        ret_dict[ind] = data

    def decode_and_decrypt(HE, t, ret_dict, ind):
        temp_file = tempfile.NamedTemporaryFile()
        enc_res = np.array(
            [[[[decode_ciphertext(value, temp_file) for value in row]
               for row in column] for column in layer] for layer in t])
        dec_res = decrypt_matrix(HE, enc_res)
        ret_dict[ind] = dec_res

    def uploadS3(msg_path, bucket, ak, sk):
        s3c = boto3.client('s3',
                           aws_access_key_id=ak,
                           aws_secret_access_key=sk)

        if '/' in msg_path:
            pos = len(msg_path) - 1
            c = msg_path[pos]
            while (c != '/'):
                pos -= 1
                c = msg_path[pos]
            pos += 1
        ts = str(datetime.datetime.now()).replace(' ', '_').replace(
            ':', '-').replace('.', '-')
        try:
            in_file_name = 'input_payload_{}'.format(ts)
            s3c.upload_file(msg_path, bucket, 'input/{}'.format(in_file_name))
            return in_file_name
        except:
            raise Exception("error while uploading {}".format(msg_path))

    address = parameters["address"]
    ak = parameters["ak"]
    sk = parameters["sk"]
    bk = parameters["bk"]

    encryption_parameters = parameters["encryption_parameters"]

    max_threads = parameters["max_threads"]

    temp_file_payload = tempfile.NamedTemporaryFile()

    HE = Pyfhel()
    HE.contextGen(m=encryption_parameters[0]["m"],
                  p=encryption_parameters[0]["p"],
                  sec=encryption_parameters[0]["sec"],
                  base=encryption_parameters[0]["base"])
    HE.keyGen()

    manager = multiprocessing.Manager()
    return_dict = manager.dict()
    processes = []

    distributions = []

    if len(data) % max_threads == 0:
        n_threads = max_threads
        subtensors_dim = len(data) // n_threads
        for i in range(0, n_threads):
            distributions.append(
                [i * subtensors_dim, i * subtensors_dim + subtensors_dim])
    else:
        n_threads = min(max_threads, len(data))
        subtensors_dim = len(data) // n_threads
        for i in range(0, n_threads):
            distributions.append(
                [i * subtensors_dim, i * subtensors_dim + subtensors_dim])
        for k in range(0, (len(data) % n_threads)):
            distributions[k][1] += 1
            distributions[k + 1::] = [[x + 1, y + 1]
                                      for x, y in distributions[k + 1::]]

    for i in range(0, n_threads):
        processes.append(
            multiprocessing.Process(
                target=crypt_and_encode,
                args=(HE, data[distributions[i][0]:distributions[i][1]],
                      return_dict, i)))
        processes[-1].start()

    for p in processes:
        p.join()

    data = np.array(return_dict[0])
    for i in range(1, n_threads):
        data = np.concatenate((data, return_dict[i]))

    payload = parameters
    payload["data"] = data.tolist()

    with open(temp_file_payload.name, 'w') as fp:
        json.dump(payload, fp)

    remote_filename = uploadS3(temp_file_payload.name, bk, ak, sk)

    msg = {
        "access_key": ak,
        "secret_key": sk,
        "bucket": bk,
        "filename": remote_filename
    }
    jmsg = json.dumps(msg)

    r = requests.post(address, jmsg)

    if r.status_code == 200:
        print("Done.")
        out_file = r.json()

    print("Downloading response...")

    s3r = boto3.resource('s3', aws_access_key_id=ak, aws_secret_access_key=sk)

    obj = s3r.Object(bk, 'output/{}'.format(out_file))
    resp_payload = json.load(obj.get()['Body'])

    print("Cleaning S3 support files...")
    inp_tbd = s3r.Object(bk, "input/{}".format(remote_filename))
    out_tbd = s3r.Object(bk, "output/{}".format(out_file))
    inp_tbd.delete()
    out_tbd.delete()
    print("Done.")

    enc_result = resp_payload["data"]

    return_dict = manager.dict()
    processes = []
    for i in range(0, n_threads):
        processes.append(
            multiprocessing.Process(
                target=decode_and_decrypt,
                args=(HE, enc_result[distributions[i][0]:distributions[i][1]],
                      return_dict, i)))
        processes[-1].start()

    for p in processes:
        p.join()

    result = np.array(return_dict[0])
    for i in range(1, n_threads):
        result = np.concatenate((result, return_dict[i]))

    return result
Exemple #30
0
def remote_execution_rest(data, parameters):

    encryption_parameters = parameters["encryption_parameters"]
    address = parameters["address"]
    max_threads = parameters["max_threads"]

    def encode_ciphertext(c, temp_file):
        with (open(temp_file.name, "w+b")) as f:
            c.save(temp_file.name)
            bc = f.read()
            b64 = str(base64.b64encode(bc))[2:-1]
            return b64

    def decode_ciphertext(b64, temp_file):
        with (open(temp_file.name, "w+b")) as f:
            x = bytes(b64, encoding='utf-8')
            x = base64.decodebytes(x)
            f.write(x)
            c = HE.encryptFrac(0)
            c.load(temp_file.name, "float")
            return c

    def crypt_and_encode(HE, t, ret_dict=None, ind=None):
        temp_file = tempfile.NamedTemporaryFile()
        enc_image = encrypt_matrix(HE, t)

        if len(enc_image.shape) > 2:
            data = [[[[encode_ciphertext(value, temp_file) for value in row]
                      for row in column] for column in layer]
                    for layer in enc_image]
        else:
            data = [[encode_ciphertext(value, temp_file) for value in row]
                    for row in enc_image]

        data = np.array(data)

        if ret_dict is not None:
            ret_dict[ind] = data
        else:
            return data

    def decode_and_decrypt(HE, t, ret_dict=None, ind=None):
        temp_file = tempfile.NamedTemporaryFile()
        t = np.array(t)
        if len(t.shape) > 2:
            enc_res = np.array(
                [[[[decode_ciphertext(value, temp_file) for value in row]
                   for row in column] for column in layer] for layer in t])
        else:
            enc_res = np.array(
                [[decode_ciphertext(value, temp_file) for value in row]
                 for row in t])

        dec_res = decrypt_matrix(HE, enc_res)
        if ret_dict is not None:
            ret_dict[ind] = dec_res
        else:
            return dec_res

    HE = Pyfhel()
    HE.contextGen(m=encryption_parameters[0]["m"],
                  p=encryption_parameters[0]["p"],
                  sec=encryption_parameters[0]["sec"],
                  base=encryption_parameters[0]["base"])
    HE.keyGen()

    if max_threads == 1:
        data = crypt_and_encode(HE, data)

        payload = parameters
        payload["data"] = data.tolist()

        json_payload = jsonpickle.encode(payload)
        res = requests.post(address, json=json_payload)

        enc_result = jsonpickle.decode(res.content)["data"]

        result = decode_and_decrypt(HE, enc_result)

        return result

    else:
        manager = multiprocessing.Manager()
        return_dict = manager.dict()
        processes = []

        distributions = []

        if len(data) % max_threads == 0:
            n_threads = max_threads
            subtensors_dim = len(data) // n_threads
            for i in range(0, n_threads):
                distributions.append(
                    [i * subtensors_dim, i * subtensors_dim + subtensors_dim])
        else:
            n_threads = min(max_threads, len(data))
            subtensors_dim = len(data) // n_threads
            for i in range(0, n_threads):
                distributions.append(
                    [i * subtensors_dim, i * subtensors_dim + subtensors_dim])
            for k in range(0, (len(data) % n_threads)):
                distributions[k][1] += 1
                distributions[k + 1::] = [[x + 1, y + 1]
                                          for x, y in distributions[k + 1::]]

        for i in range(0, n_threads):
            processes.append(
                multiprocessing.Process(
                    target=crypt_and_encode,
                    args=(HE, data[distributions[i][0]:distributions[i][1]],
                          return_dict, i)))
            processes[-1].start()

        for p in processes:
            p.join()

        data = np.array(return_dict[0])
        for i in range(1, n_threads):
            data = np.concatenate((data, return_dict[i]))

        payload = parameters
        payload["data"] = data.tolist()

        json_payload = jsonpickle.encode(payload)
        res = requests.post(address, json=json_payload)

        enc_result = jsonpickle.decode(res.content)["data"]

        return_dict = manager.dict()
        processes = []
        for i in range(0, n_threads):
            processes.append(
                multiprocessing.Process(
                    target=decode_and_decrypt,
                    args=(HE,
                          enc_result[distributions[i][0]:distributions[i][1]],
                          return_dict, i)))
            processes[-1].start()

        for p in processes:
            p.join()

        result = np.array(return_dict[0])
        for i in range(1, n_threads):
            result = np.concatenate((result, return_dict[i]))

        return result