# CSE 142 Exploration Session # Modular arithmetic # Gets a message from the user and encrypts/decrypts it using RSA. # This is pretty weak because we're only encrypting 8 bits at a time # and using small primes. Industrial strength RSA would encrypt 2048+ bits # at a time and use much larger primes. # P and Q the two primes we'll use to generate our key pair P = 61 Q = 53 N = P * Q Z = (P - 1) * (Q - 1) # (N,E) and (N,D) are our public and private keys E = 17 D = 2753 # encrypte a message # here we're encrypting each character which is weak # if we used larger primes we could encrypt chunks of characters # rather than only individual characters # here we use E for exponentiation def encrypt(s) result = '' s.each_byte do |b| b = b ** E % N r = b.to_s while r.length < 4 r = '0' + r end result += r end return result end # decryptes a message # here we use D for exponentiation def decrypt(s) result = '' for i in 0...(s.length / 4) r = s.slice(i * 4, 4) r = r.to_i ** D % N result += r.chr end return result end def main() print 'Message to encrypt/decrypt: ' message = gets() puts "Message: #{message}" encrypted = encrypt(message) puts "Encrypted: #{encrypted}" decrypted = decrypt(encrypted) puts "Decrypted: #{decrypted}" puts "Decrypted matches original: #{message == decrypted}" end main()