postheadericon RSA Encryption Example in Java

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
//sensitive information
   byte[] text = s.getBytes();

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

public String doDecryption(byte[] s)throws Exception

   // Initialize the same cipher for decryption

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

return(new String(textDecrypted));

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
  • execute

Follow by Email

Blog Archive

Total Pageviews

© Powered by Blogger.