Content

Programming and other nerdy things!

RSA Encryption with Python (full)

Wednesday 31 October 2012 - Filed under Code Snippet + Encryption + Python + Security + Utility

Plain and simple, rsa encryption in python. Not the best implementation, I’m sure but it seems to work ok-ish. Feel free to modify, re-distribute or even upgrade it!

mod.py

#!/usr/bin/env Python

def replace_string(string):
	values = {"a": "10", "b": "11", "c": "12", "d": "13", "e": "14", "f": "15", "g": "16", "h": "17", "i": "18", "j": "19", "k": "20", "l": "21", "m": "22", "n": "23", "o": "24", "p": "25", "q": "26", "r": "27", "s": "28", "t": "29", "u": "30", "v": "31", "w": "32", "x": "33", "y": "34", "z": "35", " ": "36", "?": "37", "!": "38", ",": "39", ".": "40"}
	output = ""
	
	for x in list(string):
		output += str(int(values.get(str.lower(x))))
		
	return output
	
def revert_string(string):
	values = {"10": "a", "11": "b", "12": "c", "13": "d", "14": "e", "15": "f", "16": "g", "17": "h", "18": "i", "19": "j", "20": "k", "21": "l", "22": "m", "23": "n", "24": "o", "25": "p", "26": "q", "27": "r", "28": "s", "29": "t", "30": "u", "31": "v", "32": "w", "33": "x", "34": "y", "35": "z", "36": " ", "37": "?", "38": "!", "39": ",", "40": "."}
	output = ""
	count = 0
	x = 0 
	
	while count < len(string):
		output += str(values.get(string[count:(count+2)]))
		count += 2
		
	return output

mr_test.py (primes)

import random
 
_mrpt_num_trials = 5 # number of bases to test
 
def is_prime(n):
    assert n >= 2
	
    if n == 2:
        return True
		
    if n % 2 == 0:
        return False
		
    s = 0
    d = n-1
    while True:
        quotient, remainder = divmod(d, 2)
        if remainder == 1:
            break
        s += 1
        d = quotient
    assert(2**s * d == n-1)
	
    def try_composite(a):
        if pow(a, d, n) == 1:
            return False
        for i in range(s):
            if pow(a, 2**i * d, n) == n-1:
                return False
        return True
 
    for i in range(_mrpt_num_trials):
        a = random.randrange(2, n)
        if try_composite(a):
            return False
 
    return True
		
def extEuclideanAlg(a, b) :
  if b == 0 :
      return 1,0,a
  else :
      x, y, gcd = extEuclideanAlg(b, a % b)
      return y, x - y * (a // b),gcd

def modInv(a,m) :
  x,y,gcd = extEuclideanAlg(a,m)
  if gcd == 1 :
      return x % m
  else :
      return None
	  
def splitter(string):
	length = len(str(string))
	parts = []
	if (length % 2) != 0:
		return 0
	else:
		count = 0
		while count < length:
			parts.append(str(string)[count:(count+2)])
			count += 2
			
	return parts

rsa.py

#!/usr/bin/env Python

import random
import mr_test as mra
import mod

class RSAEncrypt():
	def __init__(self):
		self.val_d = 0
		self.mod_n = 0
		self.int_e = 0
		self.phi_n = 0
		self.prime_p = 0
		self.prime_q = 0
		self.val_c = 0
		self.lowrange = 0
		self.highrange = 0
		
	def get_prime(self, lowrange, highrange):
		val = random.randint(lowrange, highrange)
		if mra.is_prime(val):
			return val
		else:
			return self.get_prime(lowrange, highrange)
			
	def distinct_prime(self, a, b, lowrange, highrange):
		while a == b:
			b = self.get_prime(lowrange, highrange)
			if b == a:
				continue
			else:
				break
				
		return b
		
	def generate(self, string):
		self.lowrange = int(string)/2
		self.highrange = int(string)*2
		self.string = string
		
		prime_p = self.get_prime(self.lowrange, self.highrange)
		prime_q = self.get_prime(self.lowrange, self.highrange)
		prime_q = self.distinct_prime(prime_p, prime_q, self.lowrange, self.highrange)
		
		self.prime_p = prime_p
		self.prime_q = prime_q
		
		mod_n = (prime_p)*(prime_q)
		phi_n = (prime_p-1)*(prime_q-1)
		int_e = 65537
		
		self.mod_n = mod_n
		self.int_e = int_e
		self.phi_n = phi_n
		
		val_d = mra.modInv(int_e, phi_n)
		self.val_d = val_d
		
		return val_d, mod_n
		
	def encrypt(self, string):
		message = string
		val_c = (int(message)**self.int_e)%self.mod_n
		return val_c
		
	def decrypt(self, message, key, modu):
		val_m = (message**key)%modu
		return val_m
		

if __name__ == "__main__":
	string = mod.replace_string("hello, world!")
	message = mra.splitter(string)
	counter = 0
	rsa = RSAEncrypt()
	
	decrypted = ""
	key = []
	msg = []
	modval = []
	
	# encryption
	for x in message:
		kval = rsa.generate(x)
		mval = rsa.encrypt(x)
		modval.append(kval[1])
		key.append(kval[0])
		msg.append(mval)
		
	# decryption
	for y in msg:
		decrypted += str(rsa.decrypt(y, key[counter], modval[counter]))
		counter += 1
		
	print decrypted
	print mod.revert_string(decrypted)

2012-10-31  »  mono