Skip to content

Instantly share code, notes, and snippets.

@ykm11 ykm11/
Last active Oct 19, 2018

What would you like to do?
from useless.math import *
from Crypto.Util.number import *
import random
def gen_key(bits):
p = getPrime(bits); q = getPrime(bits)
n = p*q
k = random.randint(2, n)
g = (1 + k*n) % (n**2)
print("[+] (p, q) :", (p, q))
print("[+] g :", g)
return p, q, n, k, g
def L(u):
return (u-1)//n
def LMD(p, q): # p and q are respectively prime
g = gcd(p-1, q-1)
return (p-1)*(q-1)//g
def enc(m):
r = random.randint(2, n**2)
s = pow(g, m, n**2)
t = pow(r, n, n**2)
return s*t % (n**2)
def dec(c):
s = L(pow(c, LMD(p, q), n**2))
t = L(pow(g, LMD(p, q), n**2))
return s * modinv(t, n) % n
p, q, n, k, g = gen_key(1024)
assert gcd(L(pow(g, LMD(p, q), n**2)), n) == 1
m1 = 114
m2 = 514
assert dec(enc(m1)) == m1
assert dec(enc(m2)) == m2
c1 = enc(m1)
c2 = enc(m2)
print(dec(c1*c2) == m1+m2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.