postheadericon RSA Encryption Example in Java

RSA.java

import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
class RSA
{
public KeyPairGenerator keygenerator;
public KeyPair myKey;
Cipher c;
public RSA() throws Exception
{
// Genrate the Key
keygenerator = KeyPairGenerator.getInstance("RSA");
keygenerator.initialize(1024) ;
myKey = keygenerator.generateKeyPair();



// Create the cipher
c = Cipher.getInstance("RSA");


}
public byte[] doEncryption(String s) throws Exception
{

   // Initialize the cipher for encryption
   c.init(Cipher.ENCRYPT_MODE,myKey.getPublic());
 
//sensitive information
   byte[] text = s.getBytes();

// Encrypt the text
   byte[] textEncrypted = c.doFinal(text);

return(textEncrypted);
}
public String doDecryption(byte[] s)throws Exception
{

   // Initialize the same cipher for decryption
c.init(Cipher.DECRYPT_MODE,myKey.getPrivate());

   // Decrypt the text
   byte[] textDecrypted = c.doFinal(s);

return(new String(textDecrypted));
}
}



DoRSA.java

import bsr.*;
public class DoRSA
{  

public static void main(String[] argv) throws Exception
{
  RSA d=new RSA();
byte[] str=d.doEncryption("BipinRupadiya");
System.out.println("Encrypted String : "+str);
System.out.println("Encrypted String : "+d.doDecryption(str));
 
}
}


To execute this code


  • open two command prompt
  • compile bsr package
  • compile DoRSA.java
  • execute DoRSA.java


0 comments:

Blog Archive

Total Pageviews

© BipinRupadiya.com. Powered by Blogger.