[英]Encrypt in java, decrypt in node.js
I need to encrypt in java and decrypt with node.js. 我需要在Java中加密并使用node.js解密。 The decryption result is corrupted. 解密结果已损坏。
Here is the java code: 这是Java代码:
public String encrypt(SecretKey key, String message){
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] stringBytes = message.getBytes("UTF8");
byte[] raw = cipher.doFinal(stringBytes);
// converts to base64 for easier display.
BASE64Encoder encoder = new BASE64Encoder();
String base64 = encoder.encode(raw);
return base64;
}
Here is the node.js code: 这是node.js代码:
AEse3SCrypt.decrypt = function(cryptkey, encryptdata) {
encryptdata = new Buffer(encryptdata, 'base64').toString('binary');
var decipher = crypto.createDecipher('aes-128-cbc', cryptkey);
decipher.setAutoPadding(false);
var decoded = decipher.update(encryptdata);
decoded += decipher.final();
return decoded;
}
As a key I use: "[B@4ec6948c"
The jave encrypted result is: "dfGiiHZi8wYBnDetNhneBw=="<br>
The node.js result is garbich....
As a key I use: "[B@4ec6948c" 作为关键,我使用:“ [B @ 4ec6948c”
That sounds very much like you're just calling toString()
on a byte array. 这听起来非常像您只是在字节数组上调用toString()
。 That's not giving you the data within the byte array - it's just the default implementation of Object.toString()
, called on a byte array. 这并没有为您提供字节数组中的数据 ,而只是在字节数组上调用的Object.toString()
的默认实现。
Try using Arrays.toString(key)
to print out the key. 尝试使用Arrays.toString(key)
来打印密钥。
If you were using that broken key value in the node.js code, it's no wonder it's giving you garbage back. 如果您在node.js代码中使用了损坏的键值,也就不足为奇了。
I tried to remove utf8 encoding from the java in order to be complementary with the node.js 我试图从Java中删除utf8编码,以便与node.js互补
That's absolutely the wrong approach. 那绝对是错误的方法。 Instead, you should work out how to make the node.js code interpret the plaintext data as UTF-8 encoded text. 相反,您应该研究如何使node.js代码将纯文本数据解释为UTF-8编码的文本。 Fundamentally, strings are character data and encryption acts on binary data - you need a way to bridge the gap, and UTF-8 is an entirely reasonable way of doing so. 从根本上讲,字符串是字符数据,加密作用在二进制数据上-您需要一种弥合差距的方法,而UTF-8是一种完全合理的方法。 The initial result of the decryption in node.js should be binary data, which you then "decode" to text via UTF-8. node.js中解密的初始结果应该是二进制数据,然后您可以通过UTF-8将其“解码”为文本。
I'm afraid I don't know enough about the padding side to comment on that. 恐怕我对填充方面的知识还不够多,无法对此发表评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.