RSA: Fastest Process

This article is to discuss about “RSA: Fastest Process”

import binascii
import Crypto.Util.number

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():
	p, q = Crypto.Util.number.getPrime(8), Crypto.Util.number.getPrime(8)
	print p, q
	N = p*q
	phi = (p-1)*(q-1)
	// fastest process when e=1, is not about security...
	e = 1
	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 = "R"
	cipher = encrypt(str2num(plain), e, N)
	print str2num(plain)
	plains = decrypt(cipher, d, N)
	print "Cipher: ", cipher
	print "Plain: ", num2str(plains)
	assert plain == num2str(plains)

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