在我的代码中,我使用crypto.js使用AES加密加密数据,我正在解密加密文本 在java。
如果我尝试在javascript或java中加密和解密,加密和解密工作正常。但是如果我在javascript中加密 并试图在java中解密我得到低于错误。
javax.crypto.BadPaddingException:给定最终块不正确 填补 com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:966)
以下是我的JSCode:
var keyHex = CryptoJS.enc.Utf8.parse('584771624934175587013168');
var iv = CryptoJS.enc.Hex.parse('000000000000000000000000');
var encrypted = CryptoJS.AES.encrypt('1111', keyHex, {
iv:iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
console.log('encryptByAES key: ',encrypted.toString());
以下是我的java代码。
String key = "584771624934175587013168";
String plainText = "1111";
public String encryptTextusingAES(String text, String kek) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes= new byte[16];
byte[] b= kek.getBytes("UTF-8");
int len= b.length;
if (len> keyBytes.length) len = keyBytes.length;
System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.ENCRYPT_MODE,keySpec,ivSpec);
byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(results);
}
public String decryptTextusingAES(String text, String kek) throws Exception{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes= new byte[16];
byte[] b= kek.getBytes("UTF-8");
int len= b.length;
if (len> keyBytes.length) len = keyBytes.length;
System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec);
BASE64Decoder decoder = new BASE64Decoder();
byte [] results = cipher.doFinal(decoder.decodeBuffer(text));
return new String(results,"UTF-8");
}
How to decrypt correctly any help will be greatly appreciated!!!!
答案 0 :(得分:0)
当您使用AES等块加密时,您的输入需要在加密前进行填充。有各种标准方法可以做到这一点。
在您的JS代码中,您指定了PKCS-7:
//module1.js
export const a = ...
export const b = ...
export const c = ...
export const b = ...
export const myCustomConstants = { a, c };
//module2.js
import { myCustomConstants } from './someModule';
doStuff(myCustomConstants);
但在您的Java代码中,您指定的是PKCS-5:
padding: CryptoJS.pad.Pkcs7
确保您在两侧使用相同的填充算法。