RSA: More Than Two Primes

This article is to discuss about “RSA: More Than 2 Primes”

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)

rsa1

Hope it is useful…

Talk Less Code More

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s