Wednesday, 9 March 2016

Implementation of RSA Algorithm(Encryption and Decryption) in Java

Implementation of RSA Algorithm(Encryption and Decryption) in Java


JAVA Program

    1. import java.math.BigInteger;
    1. import java.util.Random;
    1. import java.io.*;
    1. public class RSA {
    1. private BigInteger p;
    1. private BigInteger q;
    1. private BigInteger N;
    1. private BigInteger phi;
    1. private BigInteger e;
    1. private BigInteger d;
    1. private int bitlength = 1024;
    1. private int blocksize = 256;
    1. //blocksize in byte
    1. private Random r;
    1. public RSA() {
    1. r = new Random();
    1. p = BigInteger.probablePrime(bitlength, r);
    1. q = BigInteger.probablePrime(bitlength, r);
    1. N = p.multiply(q);
    1. phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
    1. e = BigInteger.probablePrime(bitlength/2, r);
    1. while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0 ) {
    1. e.add(BigInteger.ONE);
    1. }
    1. d = e.modInverse(phi);
    1. }
    1. public RSA(BigInteger e, BigInteger d, BigInteger N) {
    1. this.e = e;
    1. this.d = d;
    1. this.N = N;
    1. }
    1. public static void main (String[] args) throws IOException {
    1. RSA rsa = new RSA();
    1. DataInputStream in=new DataInputStream(System.in);
    1. String teststring ;
    1. System.out.println("Enter the plain text:");
    1. teststring=in.readLine();
    1. System.out.println("Encrypting String: " + teststring);
    1. System.out.println("String in Bytes: " + bytesToString(teststring.getBytes()));
    1. // encrypt
    1. byte[] encrypted = rsa.encrypt(teststring.getBytes());
    1. System.out.println("Encrypted String in Bytes: " + bytesToString(encrypted));
    1. // decrypt
    1. byte[] decrypted = rsa.decrypt(encrypted);
    1. System.out.println("Decrypted String in Bytes: " + bytesToString(decrypted));
    1. System.out.println("Decrypted String: " + new String(decrypted));
    1. }
    1. private static String bytesToString(byte[] encrypted) {
    1. String test = "";
    1. for (byte b : encrypted) {
    1. test += Byte.toString(b);
    1. }
    1. return test;
    1. }
    1. //Encrypt message
    1. public byte[] encrypt(byte[] message) {
    1. return (new BigInteger(message)).modPow(e, N).toByteArray();
    1. }
    1. // Decrypt message
    1. public byte[] decrypt(byte[] message) {
    1. return (new BigInteger(message)).modPow(d, N).toByteArray();
    1. }
    1. }

No comments:

Post a Comment