def test_e_add():
    for i in range(5):
        priv, pub = paillier.generate_keypair(128)
        for j in range(5):
            a = long(random.randint(0, 1000000))
            b = long(random.randint(0, 1000000))
            ca, cb = paillier.encrypt(pub, a), paillier.encrypt(pub, b)
            cs = paillier.e_add(pub, ca, cb)
            s = paillier.decrypt(priv, pub, cs)
            assert a + b == s
Exemple #2
0
def test_e_add():
    for i in range(5):
        priv, pub = paillier.generate_keypair(128)
        for j in range(5):
            a = long(random.randint(0, 1000000))
            b = long(random.randint(0, 1000000))
            ca, cb = paillier.encrypt(pub, a), paillier.encrypt(pub, b)
            cs = paillier.e_add(pub, ca, cb)
            s = paillier.decrypt(priv, pub, cs)
            assert a + b == s
def test_add():
    private_key, public_key = create_key_pair(bit_length=TEST_BIT_LENGTH)
    a = 123
    b = 37
    expected = (123 + 37) % public_key.n

    ciphertext_a = encrypt(public_key, a)
    ciphertext_b = encrypt(public_key, b)

    encrypted_result = add(public_key, ciphertext_a, ciphertext_b)
    result = decrypt(private_key, public_key, encrypted_result)

    assert result == expected
Exemple #4
0
def test_decrypt():
    for i in range(5):
        priv, pub = paillier.generate_keypair(64)
        for j in range(5):
            pt = long(random.randint(0, 1000000))
            ct = paillier.encrypt(pub, pt)
            assert pt == paillier.decrypt(priv, pub, ct)
def test_decrypt():
    for i in range(5):
        priv, pub = paillier.generate_keypair(64)
        for j in range(5):
            pt = long(random.randint(0, 1000000))
            ct = paillier.encrypt(pub, pt)
            assert pt == paillier.decrypt(priv, pub, ct)
Exemple #6
0
def bob_round_2(pi, m, alpha, zeta, r, k2, x2, r2, y1, y2, ka_pub, kb_pub, zkp):
    n, g = ka_pub
    n2 = n * n

    rq = r[0] % ecdsa.n
    if rq == 0:
        print("signature failed, retry")
        exit(1)

    z2 = utils.invert(k2, ecdsa.n)
    x2z2 = (x2 * z2) % ecdsa.n
    x3 = utils.randomnumber(pow(ecdsa.n, 5)-1, inf=1)

    if not eczkp.pi_verify(pi, r, ecdsa.G, r2, y1, alpha, zeta, zkp, ka_pub):
        print "Error: zkp failed"
        exit(1)

    mu1 = paillier.mult(alpha, m * z2, n2)
    mu2 = paillier.mult(zeta, rq * x2z2, n2)
    mu3, rnumb = paillier.encrypt(x3 * ecdsa.n, ka_pub)
    mu = paillier.add(paillier.add(mu1, mu2, n2), mu3, n2)

    muprim, rmuprim = paillier.encrypt(z2, kb_pub)

    c = r2
    d = ecdsa.G
    w1 = ecdsa.G
    w2 = y2
    m1 = muprim # ENCRYPTED Z2
    m2 = mu # ENCRYPTED RESULT
    m3 = alpha # ENCRYPTED Z1
    m4 = zeta # ENCRYPTED X1Z1
    r1 = rmuprim
    r2 = rnumb
    x1 = z2
    x2 = x2z2
    x4 = m
    x5 = rq

    pi2 = eczkp.pi2(c, d, w1, w2, m1, m2, m3, m4, r1, r2, x1, x2, x3, x4, x5, zkp, ka_pub, kb_pub)
    if not pi2:
        print "Error: zkp failed"
        exit(1)

    return mu, muprim, pi2
def test_encrypt_and_decrypt():
    private_key, public_key = create_key_pair(bit_length=TEST_BIT_LENGTH)
    plaintext = 123

    ciphertext = encrypt(public_key, plaintext)
    assert ciphertext != plaintext

    decrypted = decrypt(private_key, public_key, ciphertext)
    assert decrypted == plaintext
Exemple #8
0
def test_e_mul_const():
    for i in range(5):
        priv, pub = paillier.generate_keypair(128)
        for j in range(5):
            a = long(random.randint(0, 1000000))
            c = paillier.encrypt(pub, a)
            for n in range(0, 11):
                cs = paillier.e_mul_const(pub, c, n)
                s = paillier.decrypt(priv, pub, cs)
                assert a * n == s
def test_e_mul_const():
    for i in range(5):
        priv, pub = paillier.generate_keypair(128)
        for j in range(5):
            a = long(random.randint(0, 1000000))
            c = paillier.encrypt(pub, a)
            for n in range(0, 11):
                cs = paillier.e_mul_const(pub, c, n)
                s = paillier.decrypt(priv, pub, cs)
                assert a * n == s
def test_multiply():
    private_key, public_key = create_key_pair(bit_length=TEST_BIT_LENGTH)
    a = 123
    b = 25
    expected = (123 * 25) % public_key.n

    ciphertext_a = encrypt(public_key, a)
    encrypted_result = multiply(public_key, ciphertext_a, b)
    result = decrypt(private_key, public_key, encrypted_result)

    assert result == expected
def encryptFP(pb, x):
    """
	x = 3.54 or 23.12 or 23
	returns an obj of type FloatingPoint, after encrypting x with pb
	"""
    f = 15
    e = -f
    x = int(x * (10**f))
    while x % 10 == 0:
        x = x // 10
        e += 1
    return FloatingPoint(paillier.encrypt(pb, x), e)
def encrypted_celsius_to_fahrenheit(public_key: PublicKey,
                                    ciphertext: int) -> int:
    """
    Returns an encrypted integer representing 1/10ths of a degree Fahrenheit
    °F = °C * 1.8 + 32
    """
    # First multiply the ciphertext by 18.
    multiplied_by_18 = multiply(public_key, ciphertext, 18)
    # Now encrypt 320.
    encrypted_320 = encrypt(public_key, 320)
    # Finally add them together. The result will need to be divided by 10.
    return add(public_key, multiplied_by_18, encrypted_320)
Exemple #13
0
def bob_round_2(pi, m, alpha, zeta, r, k2, x2, r2, y1, y2, ka_pub, kb_pub,
                zkpa, zkpb):
    n, g = ka_pub
    n2 = n * n
    rq = r % dsa.Q
    N, h1, h2 = zkpa
    if rq == 0:
        print("signature failed, retry")
    z2 = utils.invert(k2, dsa.Q)
    x2z2 = (x2 * z2) % dsa.Q
    c = x3 = utils.randomnumber(pow(dsa.Q, 5) - 1, inf=1)

    if not zkp.pi_verify(pi, r, dsa.G, r2, y1, alpha, zeta, N, h1, h2, ka_pub):
        return False

    mu1 = paillier.mult(alpha, (m * z2) % dsa.Q, n2)
    mu2 = paillier.mult(zeta, (rq * x2z2) % dsa.Q, n2)
    mu3, rnumb = paillier.encrypt(c * dsa.Q, ka_pub)
    mu = paillier.add(paillier.add(mu1, mu2, n2), mu3, n2)

    muprim, rmuprim = paillier.encrypt((m * z2) % dsa.Q, kb_pub)

    c = r2
    d = dsa.G
    w2 = y2
    m1 = muprim
    m2 = mu
    m3 = alpha
    m4 = zeta
    r1 = rmuprim
    r2 = rnumb
    x1 = z2
    x2 = (rq * x2z2) % dsa.Q
    w1 = dsa.G

    pi2 = zkp.pi2(m, c, d, w1, w2, m1, m2, m3, m4, r1, r2, x1, x2, x3, zkpb,
                  ka_pub, kb_pub)

    return mu, muprim, pi2
def test_multiply_by_one():
    private_key, public_key = create_key_pair(bit_length=TEST_BIT_LENGTH)
    a = 123
    b = 1
    expected = 123
    ciphertext_a = encrypt(public_key, a)
    naive_encrypted_result = ciphertext_a

    encrypted_result = multiply(public_key, ciphertext_a, b)
    assert encrypted_result != naive_encrypted_result

    result = decrypt(private_key, public_key, encrypted_result)
    assert result == expected
Exemple #15
0
def Secure_Image_Adjustment_Image_negation(enc_img, l, pb):
    """
	enc_img : encrypted image
	l : encrypted L(grey levels in the range [0,L−1].)
	"""
    l = 255
    enc_l = paillier.encrypt(pb, l)
    n, m = len(enc_img), len(enc_img[0])
    ret_img = enc_img.copy()
    for i in range(n):
        for j in range(m):
            ret_img[i][j] = paillier.homomorphicSubCC(pb, enc_l, enc_img[i][j])
    return ret_img
Exemple #16
0
    def encode_y(self, pk, C, y):
        N = len(y)
        T = [0] * N
        R_prev = 0
        for i in range(N):
            D = paillier.e_add(pk, paillier.encrypt(pk, -y[i]), C[i])
            F = paillier.e_add(
                pk, paillier.e_add(pk, C[i], paillier.encrypt(pk, y[i])),
                paillier.e_mul_const(pk, C[i], -2 * y[i]))
            if i == 0:
                R = F
                R_prev = R
            else:
                R = paillier.e_add(pk, paillier.e_mul_const(pk, R_prev, 2), F)
                R_prev = R

            T[i] = paillier.e_add(
                pk,
                paillier.e_mul_const(pk, paillier.e_add_const(pk, R, -1),
                                     random.randint(0, pk.n - 1)), D)

        random.shuffle(T)
        return T
def test_encrypted_celsius_to_fahrenheit():
    private_key, public_key = create_key_pair(bit_length=TEST_BIT_LENGTH)

    temperature_in_celsius = 23
    temperature_in_fahrenheit = 73.4

    encrypted_input = encrypt(public_key, temperature_in_celsius)
    encrypted_output = encrypted_celsius_to_fahrenheit(public_key,
                                                       encrypted_input)
    decrypted_output = decrypt(private_key, public_key, encrypted_output)
    # Note that the Paillier cryptosystem only deals with integers and cannot handle
    # encrypted division because it is only a partial homomorphic encryption scheme
    scaled_output = decrypted_output / 10

    assert scaled_output == temperature_in_fahrenheit
Exemple #18
0
    def encode_x(self, pk, x):
        N = len(x)
        scheme = self.cipher_suite.scheme

        T = [[0] * N for i in range(2)]

        if scheme == "Paillier":
            for j in range(N):
                T[x[j]][j] = paillier.encrypt(pk, 0)
                # r = random.randint(0, pk.n-1)
                T[1 - x[j]][j] = paillier.random_cipher(pk)
        elif scheme == "ElGamal":
            for j in range(N):
                T[x[j]][j] = elgamal.encrypt(pk, 1)
                T[1 - x[j]][j] = elgamal.random_cipher(pk)

        return T
def encrypted_price_calculator(
    public_key: PublicKey,
    # a list of (encrypted price, plaintext quantity) tuples
    encrypted_cart: List[Tuple[int, int]],
) -> int:
    """
    Returns the encrypted sum of multiplying each encrypted price by an unencrypted quantity
    """
    item_subtotals = [
        multiply(public_key, price, quantity)
        for price, quantity in encrypted_cart
    ]

    total = encrypt(public_key, 0)
    for item_subtotal in item_subtotals:
        total = add(public_key, total, item_subtotal)

    return total
Exemple #20
0
def Secure_Noise_Reduction_LPF(enc_img, px, py, pb):
    """
	Mean filter, average over nearest n * m pixels patch
	enc_img : encrypted image
	px : patch lenght
	py : patch height
	"""
    n, m = len(enc_img), len(enc_img[0])
    ret_img = enc_img.copy()

    for i in range(n):
        for j in range(m):
            tmp_ij = paillier.encrypt(pb, 0)
            den = 0
            for ii in range(max(0, i - px), min(n - 1, i + px)):
                for jj in range(max(0, j - py), min(m - 1, j + py)):
                    den += 1
                    tmp_ij = paillier.homomorphicAddC(pb, tmp_ij,
                                                      enc_img[ii][jj])
            tmp_ij = paillier.homomorphicDivision(pb, tmp_ij, den)
            ret_img[i][j] = tmp_ij
    return ret_img


# def sobelOperator(enc_img,kerX,kerY,pb):
# 	ret_img = enc_img.copy()
# 	n,m = len(enc_img), len(enc_img[0])
# 	for i in range(n-2):
# 		for j in range(m-2):
# 			subMat = []
# 			for k in range(i,i+3):
# 				tmp = []
# 				for l in range(j,j+3):
# 					tmp.append(enc_img[k][l]);
# 				subMat.append(tmp)
# 			for k in range(len(kerX)):

# 			g = np.multiply(subMat,kerX)
# 			gx = np.sum(g)
# 			g = np.multiply(subMat,kerY)
# 			gy = np.sum(g)
# 			c[i][j] = min(255,np.sqrt(gx*gx+gy*gy))
# 	return c
def test_encrypted_price_calculator():
    private_key, public_key = create_key_pair(bit_length=TEST_BIT_LENGTH)

    cart = [
        # (price, quantity)
        (2000, 1),
        (120, 5),
        (1999, 3),
    ]
    expected_price = 8597

    # Note that the items are somewhat anonymized by the removal of the highly
    # identifying price information, but the plaintext quantity could still provide
    # information which could deanonymize the item data
    encrypted_cart = [(encrypt(public_key, price), quantity)
                      for price, quantity in cart]
    encrypted_price = encrypted_price_calculator(public_key, encrypted_cart)
    decrypted_price = decrypt(private_key, public_key, encrypted_price)

    assert decrypted_price == expected_price
Exemple #22
0
def test_encrypt_non_repeatable():
    pub = paillier.PublicKey(15484279*32451217)
    for i in range(10):
        pt = random.randint(0, 1000000)
        assert paillier.encrypt(pub, pt) != paillier.encrypt(pub, pt)
Exemple #23
0
def central_server_oblivious(x):
    """
    :param
    x: A 2-D array
            each column correspond to the result from one subsystem
    :return:
    x_mean : 1-D array
            the mean value across subsystems
    enc_time: float
            the average time for each subsystem to encrypt its result
    collect_time: float
            the time for the central server to compute the average
    dec_time: float
            the average time for each subsystem to decrypt the average send
            back from the central server.
    """

    # Get dimension
    num_subsys = x.shape[0]
    num_feature = x.shape[1]

    # cx intermediate encrypted version of x
    cx = []
    cxn = []

    # x_mean : a list, this is the returned value
    x_mean = []
    x_meann = []

    # private key and public key, the private key is a pair of prime numbers, each about 512 bits
    sk, pk = paillier.generate_keypair(512)

    t0 = time.clock()
    for i in range(0, num_subsys):
        for j in range(0, num_feature):
            if x[i,j] < 0:
                x[i,j] = -x[i,j]
                cxn.append(paillier.encrypt(pk, x[i,j]))
                cx.append(1)
            else:
                cxn.append(1)
                cx.append(paillier.encrypt(pk,x[i,j]))
    t1 = time.clock()
    enc_time = t1 - t0
    # enc_time, encryption time for all sub-system, the final reported time is for each subsystem, i.e. enc_time/num_subsys

    t0 = time.clock()
    for i in range(0, num_subsys):
        for j in range(0, num_feature):
            if j == 0:
                x_mean.append(cx[i*num_feature+j])
                x_meann.append(cxn[i*num_feature+j])
            else:
                x_mean[i] = paillier.e_add(pk, x_mean[i],cx[i*num_feature+j])
                x_meann[i] = paillier.e_add(pk, x_meann[i],cxn[i*num_feature+j])
    t1 = time.clock()
    collect_time = t1 - t0
    # collect_time : time for averaging feature values among users

    t0 = time.clock()
    x_mean = [paillier.decrypt(sk,pk,x)/num_feature for x in x_mean]
    x_meann = [paillier.decrypt(sk,pk,x)/num_feature for x in x_meann]
    t1 = time.clock()
    dec_time = t1 - t0
    # dec_time : decryption time

    x_mean = [x_mean[i] - x_meann[i] for i in range(0,len(x_mean))]

    return (x_mean, enc_time/num_subsys, collect_time, dec_time)
Exemple #24
0
def cast_vote(choice,pk, tally):
    c = paillier.encrypt(pk, choice)
    if tally ==0:
        return c
    return paillier.p_add(tally, c, pk)
Exemple #25
0
import paillier as p

priv, pub = p.generate_keypair(128)

x = p.encrypt(pub, 250)
y = p.encrypt(pub, 300)
z = p.e_add(pub, x, y)
b = p.e_sub(pub, x, y)
a = p.decrypt(priv, pub, z)
c = p.decrypt(priv, pub, b)
print(x)
print(y)
print(z)
print(a)
print(c)
Exemple #26
0
COUNTER_SIZE = 6

# determine voting messages by evaluating the splitting of
# a COUNTER_SIZE length string of bits: 001001
# candidates voting messages:		      ^  ^
vm_a = 8  # binary 16 as int
vm_b = 1  # binary 1 as int

# VA generates public key (n, g) and private key (ƛ, μ)
keys = paillier.keys(89, 53, 8537)
print("Keys:", keys)

# votes cast their votes, with int r randomly chosen by each voter
# a vote of "1" is candidate B, vote of "4" is candidate A
v1 = (paillier.encrypt(keys['n'], keys['g'], 71, vm_a))
v2 = (paillier.encrypt(keys['n'], keys['g'], 72, vm_a))
v3 = (paillier.encrypt(keys['n'], keys['g'], 73, vm_a))
v4 = (paillier.encrypt(keys['n'], keys['g'], 74, vm_b))
v5 = (paillier.encrypt(keys['n'], keys['g'], 75, vm_b))
v6 = (paillier.encrypt(keys['n'], keys['g'], 76, vm_b))
v7 = (paillier.encrypt(keys['n'], keys['g'], 77, vm_b))

# tally the votes utilising pailliers homomorphic addition property
# multiply all ciphertexts then mod n**2
print("Votes plaintext:", v1, v2, v3, v4, v5, v6, v7)

ciphertext_total = (v1 * v2 * v3 * v4 * v5 * v6 * v7) % keys['n']**2
print("Totalled votes (c):", ciphertext_total)

# now VA decrypts the total
Exemple #27
0
def cast_vote(choice, pk, tally):
    c = paillier.encrypt(pk, choice)
    if tally == 0:
        return c
    return paillier.p_add(tally, c, pk)
Exemple #28
0
 def encode_x(self, pk, x):
     N = len(x)
     C = [0] * N
     for i in range(N):
         C[i] = paillier.encrypt(pk, x[i])
     return C
Exemple #29
0
def alice_round_1(m, x1, y1, ka_pub, ka_priv):
    k1 = utils.randomnumber(dsa.Q - 1, inf=2)
    z1 = utils.invert(k1, dsa.Q)
    alpha, r1 = paillier.encrypt(z1, ka_pub)
    zeta, r2 = paillier.encrypt(x1 * z1 % dsa.Q, ka_pub)
    return k1, z1, alpha, zeta, r1, r2
def test_encrypt_non_repeatable():
    pub = paillier.PublicKey(15484279 * 32451217)
    for i in range(10):
        pt = random.randint(0, 1000000)
        assert paillier.encrypt(pub, pt) != paillier.encrypt(pub, pt)
		print "Vote for your candidate by inputting their corresponding number..."

		vote_original = int(raw_input("Vote: "))
		while vote_original not in range(1, len(crypto_dictionary["candidates"]) + 1):
			print "Invalid Vote!\n"
			vote_original = int(raw_input("Vote: "))
		
		print "You have selected to vote for:", crypto_dictionary["candidates"][vote_original][1]
		vote_verification = int(raw_input("Vote Verification: "))
		while vote_verification not in range(1, len(crypto_dictionary["candidates"]) + 1):
			print "Invalid Vote!\n"
			vote_verification = int(raw_input("Vote Verification: "))

	print " "

	message = pack_message(paillier.encrypt(crypto_dictionary["candidates"][vote_original][0], crypto_dictionary["homomorphic_public_key"]), crypto_dictionary, GLOBAL_VERBOSE)
	if message[0]:
		try:
			util.debug(GLOBAL_VERBOSE, "client_aes_id", crypto_dictionary["client_aes_id"])
			socket.send(crypto_dictionary["client_aes_id"] + "." + message[1])
		except Exception as inst:
			print "Error [ socket.send (message) ]: " + str(inst)
			sys.exit(0)
	else:
		print "--------------------------------------------------------------------------------\n"
		print message[1]
		print " "
		sys.exit(0)

	response = unpack_message(socket.recv(), crypto_dictionary, GLOBAL_VERBOSE)
	if response[0]:
Exemple #32
0
def create_enc_message(key):
    enc_message = HEEncryptedMessage()
    c, r = paillier.encrypt(123456789, key)
    enc_message['message'] = c

    hex_dump(enc_message)