Saturday, April 28, 2012

RSA code in Java

      To encrypt and decrypt a string using RSA algorithm

The following code helps the user to provide a string for encryption and decryption using RSA algorithm with the help of Big Integer in java.

Source code for RSA.java:

import java.math.BigInteger; 
import java.util.Random;
import java.io.*;
 
 
public class RSA { 
     
    private BigInteger p; 
    private BigInteger q; 
    private BigInteger N; 
    private BigInteger phi; 
    private BigInteger e; 
    private BigInteger d; 
    private int bitlength = 1024; 
    private int blocksize = 256; //blocksize in byte 
     
    private Random r; 
     public RSA() { 
        r = new Random(); 
        p = BigInteger.probablePrime(bitlength, r); 
        q = BigInteger.probablePrime(bitlength, r); 
          N = p.multiply(q); 
           
        phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE)); 
          e = BigInteger.probablePrime(bitlength/2, r); 
         
        while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0 ) { 
            e.add(BigInteger.ONE); 
        } 
 d = e.modInverse(phi);  
    } 
     
    public RSA(BigInteger e, BigInteger d, BigInteger N) { 
        this.e = e; 
        this.d = d; 
        this.N = N; 
    } 
     
    public static void main (String[] args) throws IOException

        RSA rsa = new RSA(); 
           DataInputStream in=new DataInputStream(System.in);  
        String teststring ;
         System.out.println("Enter the plain text:");
        teststring=in.readLine();
        System.out.println("Encrypting String: " + teststring); 
        System.out.println("String in Bytes: " + bytesToString(teststring.getBytes())); 
 
        // encrypt 
        byte[] encrypted = rsa.encrypt(teststring.getBytes());                   
        System.out.println("Encrypted String in Bytes: " + bytesToString(encrypted)); 
         
        // decrypt 
        byte[] decrypted = rsa.decrypt(encrypted);       
        System.out.println("Decrypted String in Bytes: " +  bytesToString(decrypted)); 
         
        System.out.println("Decrypted String: " + new String(decrypted)); 
         
    } 
 
   private static String bytesToString(byte[] encrypted) { 
        String test = ""; 
        for (byte b : encrypted) { 
            test += Byte.toString(b); 
        } 
        return test; 
    } 
     
     public byte[] encrypt(byte[] message) {      
        return (new BigInteger(message)).modPow(e, N).toByteArray(); 
    } 
       
    public byte[] decrypt(byte[] message) { 
        return (new BigInteger(message)).modPow(d, N).toByteArray(); 
    } 
     
}

OUTPUT:

14 comments:

  1. sonali what if i want to encrypt a file...

    ReplyDelete
    Replies
    1. I haven't tried programming on that but try this link..i think this will solve ur problem..
      http://www.c.happycodings.com/File_Operations/code2.html

      Delete
    2. also u can visit this site:
      http://www.flexiprovider.de/examples/ExampleRSA.html

      Delete
  2. i want to ask why if i decrease a bit length the decryption text it can be symbol? not a text?

    ReplyDelete
    Replies
    1. I didnt get your doubt..if you mean that the decrypted text on reducing the bit length is a symbol..then it is not so..Whatever text you provide as plain text is decrypted and returned!
      If not clear then do ask...thank you.

      Delete
  3. Could you please tell me the function to convert string to byte opposite to the function bytesToString used in your program.
    I really need it....

    ReplyDelete
    Replies
    1. Hey you can convert string to byte using two methods:
      parseByte() or getBytes()

      Using parseByte():
      String str="Helo";
      Byte b=Byte.parseByte(str);
      //here parseByte is the method of wrapper class Byte

      Using getBytes():
      String str = "Your string";
      byte[] array = str.getBytes();
      //This creates a byte[] array

      Delete
    2. please tell me how getBytes() method will work.and why we have used toByteArray() and bytesToString()

      Delete
  4. Thanks for sharing . i can use this in my practicals :)

    ReplyDelete
    Replies
    1. please tell me how getBytes() method will work.and why we have used toByteArray() and bytesToString()

      Delete
  5. i didn't understand
    e=BigInteger.probablePrime(bitlength/2, r);
    what it does??
    how it selects e such that it is not a factor of(p-1) and (q-1)???
    i really need it.......

    ReplyDelete
    Replies
    1. Hey!
      e=BigInteger.probablePrime(bitlength/2, r);
      is only used for generating random public key and then we check the condition for it in the next line of code:

      while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0 ) {
      e.add(BigInteger.ONE);
      } //this will select e such that it is not a factor of (p-1) and (q-1).

      If still not clear then do post it again.I will try my best to clear your doubt! :)

      Delete
  6. thanks for your answer.....!!
    if we want to encrypt or decrypt entire text file then which file class is more suitable in java???

    ReplyDelete
  7. please tell me how getBytes() method will work.and why we have used toByteArray() and bytesToString()

    ReplyDelete