Tuesday, 14 March 2017

RSA algorithm java code


  1. import java.io.DataInputStream;
  2. import java.io.IOException;
  3. import java.math.BigInteger;
  4. import java.util.Random;
  5.  
  6. public class RSA
  7. {
  8.     private BigInteger p;
  9.     private BigInteger q;
  10.     private BigInteger N;
  11.     private BigInteger phi;
  12.     private BigInteger e;
  13.     private BigInteger d;
  14.     private int        bitlength = 1024;
  15.     private Random     r;
  16.  
  17.     public RSA()
  18.     {
  19.         r = new Random();
  20.         p = BigInteger.probablePrime(bitlength, r);
  21.         q = BigInteger.probablePrime(bitlength, r);
  22.         N = p.multiply(q);
  23.         phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
  24.         e = BigInteger.probablePrime(bitlength / 2, r);
  25.         while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0)
  26.         {
  27.             e.add(BigInteger.ONE);
  28.         }
  29.         d = e.modInverse(phi);
  30.     }
  31.  
  32.     public RSA(BigInteger e, BigInteger d, BigInteger N)
  33.     {
  34.         this.e = e;
  35.         this.d = d;
  36.         this.N = N;
  37.     }
  38.  
  39.     @SuppressWarnings("deprecation")
  40.     public static void main(String[] args) throws IOException
  41.     {
  42.         RSA rsa = new RSA();
  43.         DataInputStream in = new DataInputStream(System.in);
  44.         String teststring;
  45.         System.out.println("Enter the plain text:");
  46.         teststring = in.readLine();
  47.         System.out.println("Encrypting String: " + teststring);
  48.         System.out.println("String in Bytes: "
  49.                 + bytesToString(teststring.getBytes()));
  50.         // encrypt
  51.         byte[] encrypted = rsa.encrypt(teststring.getBytes());
  52.         // decrypt
  53.         byte[] decrypted = rsa.decrypt(encrypted);
  54.         System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
  55.         System.out.println("Decrypted String: " + new String(decrypted));
  56.     }
  57.  
  58.     private static String bytesToString(byte[] encrypted)
  59.     {
  60.         String test = "";
  61.         for (byte b : encrypted)
  62.         {
  63.             test += Byte.toString(b);
  64.         }
  65.         return test;
  66.     }
  67.  
  68.     // Encrypt message
  69.     public byte[] encrypt(byte[] message)
  70.     {
  71.         return (new BigInteger(message)).modPow(e, N).toByteArray();
  72.     }
  73.  
  74.     // Decrypt message
  75.     public byte[] decrypt(byte[] message)
  76.     {
  77.         return (new BigInteger(message)).modPow(d, N).toByteArray();
  78.     }
  79. }

No comments:

Post a Comment