// 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. import java.math.*; // for BigInteger import java.util.*; // for Scanner public class RSA { // The number of Ascii characters public static final BigInteger TWO_FIVE_SIX = new BigInteger("256"); // P and Q are our two primes we use to generate the key pair public static final BigInteger P = new BigInteger("61"); public static final BigInteger Q = new BigInteger("53"); public static final BigInteger N = P.multiply(Q); public static final BigInteger Z = P.subtract(BigInteger.ONE).multiply(Q.subtract(BigInteger.ONE)); // (N,E) and (N,D) are our public and private keys private static final BigInteger E = new BigInteger("17"); public static final BigInteger D = new BigInteger("2753"); public static void main(String[] args) { // Get a message from the user to encrypt/decrypt. Scanner console = new Scanner(System.in); System.out.print("Message to encrypt/decrypt: "); String message = console.nextLine(); String encrypted = encrypt(message); System.out.println("Encrypted: " + encrypted); String decrypted = decrypt(encrypted); System.out.println("Decrypted: " + decrypted); System.out.println("Decrypted matches original: " + decrypted.equals(message)); } // Raises base to the exponent. public static BigInteger pow(BigInteger base, BigInteger exponent) { BigInteger result = BigInteger.ONE; for (BigInteger i = new BigInteger("0"); !i.equals(exponent); i = i.add(BigInteger.ONE)) { result = result.multiply(base); } return result; } // Encryptes a message on character at a time. If we had larger primes // we could work with multiple characters at a time. // Here we use E for exponentiation public static String encrypt(String s) { String result = ""; for (int i = 0; i < s.length(); i++) { BigInteger b = new BigInteger("" + (int)(s.charAt(i))); String r = pow(b, E).mod(N).toString(); while (r.length() < 4) { r = "0" + r; } result += r; } return result; } // Decryptes a message // Here we use D for exponentiation public static String decrypt(String s) { String result = ""; for (int i = 0; i < s.length() / 4; i++) { BigInteger b = new BigInteger(s.substring(i * 4, (i + 1) * 4)); result += (char)(pow(b, D).mod(N).intValue()); } return result; } }