Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Author: M&K
- */
- package Algorithms;
- import java.math.BigInteger;
- import java.util.Random;
- import java.util.Scanner;
- public class RSA {
- public static void main(String[] args) {
- // Unless you have Super computer do not set bitLength greater then 10 ( 2^10 upper bound )
- BigInteger pPrime = BigInteger.probablePrime(10,new Random()); //Generate random prime of with 2^10 as upper bound
- BigInteger qPrime = BigInteger.probablePrime(10,new Random());
- RSA(pPrime,qPrime);
- }
- public static void RSA(BigInteger p, BigInteger q){
- System.out.println("First Prime = " + p);
- System.out.println("Second Prime = " + q);
- BigInteger N = p.multiply(q);
- // Z = (p-1)*(q-1)
- BigInteger Z = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
- BigInteger e = BigInteger.ZERO; // Public key exponent, 'e' is relative prime to Z
- // GCD(e,Z) == 1 would mean that both do not have any common factors
- for (long i = 2; i < Z.longValue(); i++) {
- if(Z.gcd(BigInteger.valueOf(i)).equals(BigInteger.ONE)){
- e = BigInteger.valueOf(i);
- break;
- }
- }
- // BigInteger e = BigInteger.valueOf(65537); // Often e is chosen to be (2^16) -1 i.e 65537
- System.out.println("totient function Z = " + Z);
- System.out.println("public key e = " + e);
- // int d = modInverse(e, Z); // Private key exponent
- BigInteger d = e.modInverse(Z);
- System.out.println("private key d = " + d);
- Scanner read = new Scanner(System.in);
- int plainText = read.nextInt();
- // ct = pt^2 mode N {ct = cipher text, pt = plain text}
- // long cipherText = (long)Math.pow(plainText, e) % N;
- BigInteger cipherText = BigInteger.valueOf(plainText).pow(e.intValue()).mod(N);
- System.out.println("cipher Text " + cipherText.longValue());
- BigInteger decryptText = cipherText.pow(d.intValue()).mod(N); // pt = ct^d mod N
- System.out.println("decrypt Text " + decryptText);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement