If you use a block-chaining mode like CBC, you need to provide an IvParameterSpec to the Cipher as well.
public class EncryptionTest {
static byte[] raw = new byte[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
static SecureRandom rnd = new SecureRandom();
static IvParameterSpec iv = new IvParameterSpec(rnd.generateSeed(16));
public static void main(String[] args) {
String encrypt = encrypt("1234567890123456");
System.out.println("decrypted value:" + (decrypt("ThisIsASecretKey", encrypt)));
}
public static String encrypt(String value) {
try {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec,iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string:" + Base64.encodeBase64String(encrypted));
return Base64.encodeBase64String(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String key, String encrypted) {
try {
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec,iv);
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}