# CSC 15 RSA Decryption Lab # The Rivest-Shamir-Adleman (RSA) public key encryption algorithm works # as follows: two very large prime numbers p and q are chosen and # kept secret. Let n = p*q (the idea is that it's hard to figure out # what q and p are given n). Two more numbers, d and e, are picked so # that (e*d) % ((p-1)*(q-1)) == 1. The pair (n,e) is called the # public key or encryption key, and is used by everybody to encrypt # messages. The private key consists of the number d, which is # kept secret. A message can be represented as a number m between 0 and # n-1. To encrypt the message, compute m to the eth power mod n, # or m**e % n. To decrypt the "cipher" message c, we use c**d%n. That is, # if c = m**e%n, then c**d%n will give us the original message m. # In practice the prime numbers used for encryption are very large, with # several hundred digits. But smaller numbers are enough to illustrate # the concept. For example, we can pick the two primes to be p,q = 47,59 # and e = 17, d = 157, and n = p*q (2773). We can encode text messages # character by character using their ascii values. For example, # "hello" has the corresponding list/array of (unencrypted) ascii values: # [104, 101, 108, 108, 111] ## First we need a routine to convert a string such as "hello" into such # an array of ascii valuse. Given a single character x, ord(x) returns # the ascii value (between 1 and 127) and given an ascii value a, chr(a) # returns the corresponding character. def asciivals(s): # convert string s to array of ascii values A = [0]*len(s) i = 0 while i0: if e%2==1: ax = (ax*factor) %n factor = (factor*factor) % n e = e//2 # while n>0 return ax #expmod # new version of encode using fast expmod operation def encode2(m,e,n): return expmod(m,e,n) ## Now here is a function that encodes an array of ascii values: def encodeArray(M,e,n): C = len(M)*[0] # create array of same size as M, initial values all 0 i = 0 while i