SHARE
TWEET

Untitled

a guest Oct 21st, 2019 90 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Author: M&K
  3.  */
  4. package Algorithms;
  5.  
  6. import java.math.BigInteger;
  7. import java.util.Random;
  8. import java.util.Scanner;
  9.  
  10. public class RSA {
  11.  
  12.  
  13.     public static void main(String[] args) {
  14.  
  15.         // Unless you have Super computer do not set bitLength greater then 10 ( 2^10 upper bound )
  16.         BigInteger pPrime = BigInteger.probablePrime(10,new Random()); //Generate random prime of with 2^10 as upper bound
  17.         BigInteger qPrime = BigInteger.probablePrime(10,new Random());
  18.  
  19.         RSA(pPrime,qPrime);
  20.     }
  21.  
  22.     public static void RSA(BigInteger p, BigInteger q){
  23.         System.out.println("First Prime = " + p);
  24.         System.out.println("Second Prime = " + q);
  25.         BigInteger N = p.multiply(q);
  26.         // Z = (p-1)*(q-1)
  27.         BigInteger Z = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
  28.  
  29.         BigInteger e = BigInteger.ZERO; // Public key exponent, 'e' is relative prime to Z
  30.  
  31.         // GCD(e,Z) == 1 would mean that both do not have any common factors
  32.         for (long i = 2; i < Z.longValue(); i++) {
  33.             if(Z.gcd(BigInteger.valueOf(i)).equals(BigInteger.ONE)){
  34.                 e = BigInteger.valueOf(i);
  35.                 break;
  36.             }
  37.         }
  38.  
  39. //        BigInteger e = BigInteger.valueOf(65537); // Often e is chosen to be (2^16) -1 i.e 65537
  40.  
  41.         System.out.println("totient function Z = " + Z);
  42.         System.out.println("public key e = " + e);
  43.  
  44.  
  45. //        int d = modInverse(e, Z); // Private key exponent
  46.         BigInteger d = e.modInverse(Z);
  47.         System.out.println("private key d = " + d);
  48.  
  49.         Scanner read = new Scanner(System.in);
  50.         int plainText = read.nextInt();
  51.  
  52.         // ct = pt^2 mode N  {ct = cipher text, pt = plain text}
  53. //        long cipherText = (long)Math.pow(plainText, e) % N;
  54.         BigInteger cipherText = BigInteger.valueOf(plainText).pow(e.intValue()).mod(N);
  55.         System.out.println("cipher Text " + cipherText.longValue());
  56.  
  57.         BigInteger decryptText = cipherText.pow(d.intValue()).mod(N); // pt = ct^d mod N
  58.         System.out.println("decrypt Text " + decryptText);
  59.     }
  60.  
  61. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top