I am trying to write simple AES cipher code Encryption part is working fine but decryption part is throwing exception: Code is as folloing:
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Next {
public static void main(String []ar) throws
NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException
{
Security.addProvider(new BouncyCastleProvider());
KeyGenerator generator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = new SecureRandom();
generator.init(256, secureRandom);
SecretKey key = generator.generateKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = "abcdefghijklmnopqrstuvwxyz".getBytes("UTF-8");
byte[] cipherText = cipher.doFinal(plainText);
System.out.println(cipherText);
Cipher cipher2 = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher2.init(Cipher.DECRYPT_MODE, key);
byte[] text = cipher.doFinal(cipherText); // Exception is
//throwing here
System.out.println(text);
}
}
The exception is:
Exception in thread "main" java.security.InvalidKeyException: Parameters missing
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:470)
at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:313)
at javax.crypto.Cipher.implInit(Cipher.java:801)
at javax.crypto.Cipher.chooseProvider(Cipher.java:863)
at javax.crypto.Cipher.init(Cipher.java:1248)
at javax.crypto.Cipher.init(Cipher.java:1185)
at securityInvade.Next.main(Next.java:41)