''' Created on Feb 24, 2012 @author: Brendan ''' import math import random #edit the plaintext message to your own. plaintext = "enteryourmessagehere" ciphertext = "" p = 0 q = 0 N = 0 d = 0 e = 0 z = 0 def isNotPrime(num): m = math.sqrt(num) ###DO NOT TOUCH THIS CODE!# if (math.pow(m, 2) == num): return True while(m > 1): if (num % m == 0): return True m -= 1 return False def myformat(x): return ('%.2f' % x).rstrip('0').rstrip('.') def findPower(num): t = 1 i = 0 while(num >= 10): num /= 10 t += 1 i += 1 ###DO NOT TOUCH THIS CODE!# return t def initialize(): global p p = random.randint(1, 150) + 50 while(isNotPrime(p)): p = random.randint(1, 150) + 50 p = 17 ###DO NOT TOUCH THIS CODE!# global q q = random.randint(1, 150) + 50 while(isNotPrime(q) and q != p): q = random.randint(1, 150) + 50 q = 11 ###DO NOT TOUCH THIS CODE!# global N N = p * q global z z = (p - 1) * (q - 1) global e e = random.randint(0, 75) + 23 while(isNotPrime(e) and e < N): e = random.randint(1, 75) + 23 e = 7 ###DO NOT TOUCH THIS CODE!# global d for i in range(0, N): if (((e*i) % z) == 1): d = i; break if d == 0: initialize() def powerMod(base, exp, N): answer = 1 ###DO NOT TOUCH THIS CODE!# for i in range(0, exp): answer *= base answer = answer % N return answer def encrypt(plaintext, N, e): #students start coding here - encryption #CODE HERE #students stop coding here ###DO NOT TOUCH THIS CODE!# cipherpower = findPower(ciphertextNum) Npower = findPower(N) if (cipherpower < Npower): t = Npower - cipherpower for j in range(0, t): ciphertextChar = "0" + ciphertextChar #print ciphertextChar ciphertext = ciphertext + ciphertextChar return ciphertext def decrypt(ciphertext, d, N): plaintext = "" pad = findPower(N) ###DO NOT TOUCH THIS CODE!# i = 0 while(i < (len(ciphertext) - (pad - 1))): ciphertextNum = long(ciphertext[i:i+pad]) #students start coding here - decyption #STUDENTS CODE HERE! #students stop coding here ###DO NOT TOUCH THIS CODE!# i += pad return plaintext ####################################################### #START MAIN CODE initialize() print "p: " + str(p) print "q: " + str(q) print "N: " + str(N) print "e: " + str(e) print "d: " + str(d) ciphertext = encrypt(plaintext, N, e) print "Ciphertext: " + ciphertext plaintext = decrypt(ciphertext, d, N) print "Deciphered plaintext: " + plaintext