我正在加密一个字符串并将其存储在客户端的 cookie 中。但是当我将确切的加密字符串从 js 发送到 java 代码时,它给了我上述异常。
我用于加密和解密的代码是:
public static final String UNICODE_FORMAT = "UTF8";
public static String encrypt(String Data, SecretKeySpec skeySpec,IvParameterSpec ivspec) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
byte[] plainBytes = Data.getBytes(UNICODE_FORMAT);
byte[] encrypted = cipher.doFinal(plainBytes);
String encryption = bytesToString(encrypted);
return encryption;
}
public static String decrypt(String encryptedData,SecretKeySpec skeySpec,IvParameterSpec ivspec) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);
byte[] decryptval = hexToBytes(encryptedData);
byte[] decrypted = cipher.doFinal(decryptval);
return new String(decrypted);
}
public static String bytesToString(byte[] bytes) {
HexBinaryAdapter adapter = new HexBinaryAdapter();
String s = adapter.marshal(bytes);
return s;
}
public static byte[] hexToBytes(String hexString) {
HexBinaryAdapter adapter = new HexBinaryAdapter();
byte[] bytes = adapter.unmarshal(hexString);
return bytes;
}
你能告诉我可能是什么问题吗?我已经尝试了 stackoverflow.com 上提到的解决方案以及其他一些解决方案,但没有一个有效。我收到此错误是因为我将加密字符串发送到 JS 并且它正在更改字符串的填充?