import binascii
def num2str(n):
return hex2str(num2hex(n))
def str2num(s):
return hex2num(str2hex(s))
def num2hex(n):
return ("%x" % int(n))
def str2num(s):
return int(binascii.hexlify(s), 16)
def hex2num(h):
return int(h, 16)
def str2hex(s):
return binascii.hexlify(s)
def hex2str(s):
return binascii.unhexlify(s)
def invMod(a, n):
t = 0
newt = 1
r = n
newr = a
while newr != 0:
q = r // newr
(t, newt) = (newt, t - q * newt)
(r, newr) = (newr, r - q * newr)
if r > 1:
raise Exception('unexpected')
if t < 0:
t += n
return t
def generate():
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
e, phi, N = 29, 1, 1
for p in primes:
phi *= (p-1)
N *= p
d = invMod(e, phi)
return e, N, d
def encrypt(plain, e, N):
return pow(plain, e, N)
def decrypt(cipher, d, N):
return pow(cipher, d, N)
if __name__ == '__main__':
e, N, d = generate()
plain = "Rahasia"
cipher = encrypt(str2num(plain), e, N)
plains = decrypt(cipher, d, N)
print "Cipher: ", cipher
print "Plain: ", num2str(plains)
assert plain == num2str(plains)
print pow(N, d, N)
print pow(N+2, d, N)
print d, N