21 October 2014

Java RSA Encryption and Decryption Example

This is the sample code

package sajith.foru.rsaencryption;

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class RsaEncryption {

/**
 * Generate RSA private and public key and Encrypt/Decrypt
 *
 * @param args
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
public static void main(String[] args) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
/**
 * Generate KeyPair
 */
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048); // key size can be change to 512,1024
KeyPair kp = keyGen.genKeyPair();
/**
 * Generate private and public key
 */
PublicKey publicKey = kp.getPublic();
PrivateKey privateKey = kp.getPrivate();
/**
 * String want to be encrypted
 */
String text = "Your text Message";
Cipher cipher = Cipher.getInstance("RSA");
/**
 * Enable Encrypt mode
 */
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedData = cipher.doFinal(text.getBytes());
String encryptedText = new String(encryptedData);
System.out.println("Text Encrypted : " + encryptedText);
/**
 * Enable Decrypt mode
 */
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptDataValue = cipher.doFinal(encryptedData); // decrypted
// the
// encrypted
// data
String decryptedText = new String(decryptDataValue);
System.out.println("Text Decryted : " + decryptedText);

}



}

No comments:

Post a Comment