Definition:
RSA is an algorithm for public-key cryptography that is based on the presumed difficulty of factoring large integers, the factoring problem.
Algorithm:
Definition and Algorithm taken from Wikipedia.
- and : the primes from the key generation,
- ,
- and
- .
- (if then some libraries compute h as )
I have write a Java program implementing the RSA Public key cipher algorithm. You can use the code in case 'k' , case 'c' , case 'p' for key generation, encryption and decryption respectively.
package encryption.rsa; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; public class RSA { public static void main(String[] args) throws IOException { char selection = '3'; BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); BigInteger p; BigInteger q; BigInteger n; BigInteger phiN; BigInteger e = new BigInteger("0"); BigInteger d = new BigInteger("0"); BigInteger plain; BigInteger cipher; while (selection != 'e') { switch (selection) { case 'k': System.out.print("Enter the Value of p: "); p = new BigInteger(console.readLine()); System.out.print("Enter the Value of q: "); q = new BigInteger(console.readLine()); if (!p.isProbablePrime(4) || !q.isProbablePrime(4)) { System.out.print("p or q is a composite number!\n\n"); break; } n = p.multiply(q); phiN = p.subtract(new BigInteger("1")).multiply(q.subtract(new BigInteger("1"))); for (int i = 2; i < (phiN.intValue() / 2); i++) { if (phiN.remainder(new BigInteger(String.valueOf(i))).intValue() != 0) { e = new BigInteger(String.valueOf(i)); d = e.modInverse(phiN); break; } } System.out.print("\n\nPublic Key: {" + e.toString() + ", " + n.toString() + "}\n"); System.out.print("Private Key: {" + d.toString() + ", " + n.toString() + "}\n"); break; case 'c': System.out.print("\n\nEnter the value to Encrypt: "); plain = new BigInteger(console.readLine()); System.out.print("Enter the value of e: "); e = new BigInteger(console.readLine()); System.out.print("Enter the value of n: "); n = new BigInteger(console.readLine()); cipher = plain.modPow(e, n); System.out.print("\nThe Ciphered Value of " + plain.toString() + " is " + cipher.toString() + '.'); break; case 'p': System.out.print("\n\nEnter the value to Decrypt: "); cipher = new BigInteger(console.readLine()); System.out.print("Enter the value of d: "); d = new BigInteger(console.readLine()); System.out.print("Enter the value of n: "); n = new BigInteger(console.readLine()); plain = cipher.modPow(d, n); System.out.print("\nThe Deciphered Value of " + cipher.toString() + " is " + plain.toString() + '.'); break; } System.out.println("\n\n\nPlease Select From the Following:"); System.out.println("Generate [k]ey pair."); System.out.println("En[c]rypt."); System.out.println("Decry[p]t"); System.out.println("[E]xit"); selection = console.readLine().charAt(0); } } }
No comments:
Post a Comment