我正在编写一段用Java加密数据的代码,我需要在nodejs中解密它。我遇到了解密问题。
我将salt +加密的字节加在一起,并在java端的base64中编码。
在节点端我正在解码base64,然后切片盐和加密字节。但我在尝试解密字符串时遇到错误。任何想法?
Java加密:
private Key createKey(final byte[] salt) {
final PBEKeySpec spec = new PBEKeySpec(KEY,
salt,
20000,
256);
final SecretKey secretKey;
secretKey = keyFactory.generateSecret(spec);
return new SecretKeySpec(secretKey.getEncoded(), 'AES');
}
public String encrypt(final String message) {
final byte[] salt = secureRandom.nextBytes(SALT_LENGTH);
final Key key = createKey(salt);
final Cipher encryptingCipher = createCipher(Cipher.ENCRYPT_MODE, key, salt);
final byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);
final byte[] encryptedBytes = doFinal(encryptingCipher, messageBytes);
final byte[] data = ArrayUtils.addAll(salt, encryptedBytes);
return BaseEncoding.base64().encode(data);
}
Nodejs解密:
const decrypted = new Buffer(data, 'base64').toString('ascii');
const salt = decrypted.slice(0, AESEncryptor.SALT_LENGTH);
const encryptedBytes = decrypted.slice(AESEncryptor.SALT_LENGTH);
crypto.pbkdf2(KEY, salt, 20000, 256, (err, key) => {
var decipher = crypto.createDecipheriv('aes-256-cbc', key, salt);
var decoded = decipher.update(encryptedBytes, 'binary', 'utf8') + decipher.final('utf8');
console.log('decoded', decoded);
});
这就是我得到的错误:
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt