/
paillier_gmpy2.py
60 lines (48 loc) · 1.6 KB
/
paillier_gmpy2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
'''
Created on Feb 25, 2014
@author: NASSAR
'''
import random, sys
from primes_gmpy2 import generate_prime
from gmpy2 import mpz, powmod, invert, is_prime, random_state, mpz_urandomb, rint_round, log2, gcd
rand=random_state(random.randrange(sys.maxint))
class PrivateKey(object):
def __init__(self, p, q, n):
self.l = (p-1) * (q-1)
self.m = invert(self.l, n)
class PublicKey(object):
def __init__(self, n):
self.n = n
self.n_sq = n * n
self.g = n + 1
self.bits=mpz(rint_round(log2(self.n)))
def generate_keypair(bits):
p = generate_prime(bits / 2)
q = generate_prime(bits / 2)
n = p * q
return PrivateKey(p, q, n), PublicKey(n)
def encrypt(pub, plain):
while True:
r=mpz_urandomb(rand, pub.bits)
if r > 0 and r < pub.n and gcd(r,pub.n)==1:
break
# else:
# print r
# for sufficiently large pub.bits comment the previous while True loop and uncomment the following line
# r=mpz_urandomb(rand, pub.bits)
x = powmod(r, pub.n, pub.n_sq)
cipher = (powmod(pub.g, plain, pub.n_sq) * x) % pub.n_sq
return cipher
def e_add(pub, a, b):
"""Add one encrypted integer to another"""
return a * b % pub.n_sq
def e_add_const(pub, a, n):
"""Add constant n to an encrypted integer"""
return a * powmod(pub.g, n, pub.n_sq) % pub.n_sq
def e_mul_const(pub, a, n):
"""Multiplies an encrypted integer by a constant"""
return powmod(a, n, pub.n_sq)
def decrypt(priv, pub, cipher):
x = powmod(cipher, priv.l, pub.n_sq) - 1
plain = ((x // pub.n) * priv.m) % pub.n
return plain