我正在尝试使用 AES 加密和解密字符串,但出现错误,我不知道如何解决。这是代码:
public class EncryptionTest{
public static void main(String[] args) {
String encrypt = new String(encrypt("1234567890123456"));
System.out.println("decrypted value:" + (decrypt("ThisIsASecretKey",encrypt)));
}
public static String encrypt(String value) {
try {
byte[] raw = new byte[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string:" + (new String(encrypted)));
return new String(skeySpec.getEncoded());
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String key, String encrypted) {
try {
SecretKeySpec skeySpec = new SecretKeySpec(Base64.decodeBase64(key), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(skeySpec.getEncoded(),"AES"));
(*)
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
original.toString();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
当我运行它时,“解密”值为空。它在 (***) 之前失败了!!
它给了我一个例外:
java.security.InvalidKeyException:缺少参数 在 com.sun.crypto.provider.CipherCore.init(CipherCore.java:388) 在 com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:186) 在 javax.crypto.Cipher.implInit(Cipher.java:787) 在 javax.crypto.Cipher.chooseProvider(Cipher.java:849) 在 javax.crypto.Cipher.init(Cipher.java:1213) 在 javax.crypto.Cipher.init(Cipher.java:1153) 在firma.XmlEncryptionTest.decrypt(EncryptionTest.java:63) 在firma.XmlEncryptionTest.main(EncryptionTest.java:41)
其中第 63 行是 (***) 之前的行。我不知道我做错了什么以及如何解决。我在互联网上环顾四周,但没有发现丢失的参数可能是什么