使用cryptojs的Java到JS和JS到Java加密
现在,我需要执行相反的操作,但是一旦在Java中,我就会收到此异常:
javax.crypto.BadPaddingException: Given final block not properly paddedat com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:966)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
这是我在JavaScript中执行的“反向”操作:
var rkEncryptionKey = CryptoJS.enc.Base64.parse('u/Gu5posvwDsXUnV5Zaq4g==');var rkEncryptionIv = CryptoJS.enc.Base64.parse('5D9r9ZVzEYYgha93/aUK2w==');
function encryptString(stringToEncrypt) {
var utf8Stringified = CryptoJS.enc.Utf8.parse(stringToEncrypt);
var encrypted = CryptoJS.AES.encrypt(utf8Stringified.toString(), rkEncryptionKey, {mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv: rkEncryptionIv});
return CryptoJS.enc.Base64.parse(encrypted.toString()).toString();
}
我虽然就这些了?
加密的字符串如下:
{"company_name":"asdfasdfasd","customer_name":"asdfasdfasdfasdf","phone_number":"asdfasdfasdfasdf","email":"asdfasdfasdfasdfads"}
从Java到Java进行加密/解密时,从Java到javascript也可以,但是从javascript到Java,则不起作用。
public String toJson(final String encrypted) { try {
SecretKey key = new SecretKeySpec(Base64.decodeBase64("u/Gu5posvwDsXUnV5Zaq4g=="), "AES");
AlgorithmParameterSpec iv = new IvParameterSpec(Base64.decodeBase64("5D9r9ZVzEYYgha93/aUK2w=="));
byte[] decodeBase64 = Base64.decodeBase64(encrypted);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return new String(cipher.doFinal(decodeBase64), "UTF-8");
} catch (Exception e) {
throw new RuntimeException("This should not happen in production.", e);
}
}
回答:
更改
return CryptoJS.enc.Base64.parse(encrypted.toString()).toString();
至
return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
该encrypted
对象通常字符串化为OpenSSL格式,其中也可能包含盐。如果您只对实际密文感兴趣,则需要对ciphertext
属性进行字符串化。
注意,这toString()
需要一个可选的编码功能。使用您需要的那个。
以上是 使用cryptojs的Java到JS和JS到Java加密 的全部内容, 来源链接: utcz.com/qa/428325.html