package bouncyCastle.encrypt;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class EncryptDecryptDemo {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator keyGen = null;
keyGen = KeyPairGenerator.getInstance("RSA", "BC");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
String inputString = "Hello World";
//*****************Encryption*****************
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding","BC");
cipher.init(Cipher.ENCRYPT_MODE, pub);
byte[] input = inputString.getBytes();
cipher.update(input);
byte[] cipherText = cipher.doFinal(); //Encrypted Text
System.out.println("The Encrypted Text is : "+new String(cipherText));
//*****************Decryption*****************
cipher.init(Cipher.DECRYPT_MODE, priv);
byte[] decipheredText = cipher.doFinal(cipherText);
System.out.println("The Decrypted text is "+new String(decipheredText));
}
}