我需要用 Java 翻译以下代码:
public static String encode(String chave, final String value)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
final Key keySpec = new SecretKeySpec(chave.getBytes(), "AES");
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
System.out.println(Hex.encodeHex(new byte[16]));
cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(new byte[16]));
final byte[] message = cipher.doFinal(value.getBytes());
return new String(Hex.encodeHex(message));
}
到 Node 。我正在尝试:
var encrypt = function (key, data) {
var iv = new Buffer('');
decodeKey = new Buffer(key, "utf-8");
var cipher = crypto.createCipher('aes-128-cbc', decodeKey, iv);
cipher.setAutoPadding(true);
//return cipher.update(data, 'utf8', 'hex') + ' ' + cipher.final('hex');
var encrypted = Buffer.concat([
cipher.update(data, "binary"),
cipher.final()
]);
return encrypted.toString('hex');
};
但是结果并不一样。看起来 iv 缓冲区有问题,但我无法弄清楚。
最佳答案
您有两个问题。如果您想提供 IV,则需要调用 crypto.createCipheriv
而不是 crypto.createCipher
。后者采用密码而不是 key ,并使用 OpenSSL 的 EVP_BytesToKey 从中派生 key 和 IV。
另一个问题是您应该使用正确长度的 IV:var iv = Buffer.alloc(16);
其他问题可能是到处都是编码:
value.getBytes()
使用默认的字符编码,并且可能因机器而异。始终定义特定的字符编码,例如:value.getBytes("UTF-8")
cipher.update(data, "binary")
假定data
采用 Latin1 编码,与 Java 代码不匹配。使用cipher.update(data, "utf-8")
。decodeKey = new Buffer(key, "utf-8");
看起来很糟糕,因为应该随机选择 key 。 key 的二进制表示通常不会产生有效的 UTF-8 编码。请记住, key 不是密码。
安全考虑:
IV 必须是不可预测的(读作:随机)。不要使用静态 IV,因为这会使密码具有确定性,因此在语义上不安全。观察密文的攻击者可以确定之前何时发送过相同的消息前缀。 IV 不是 secret 的,因此您可以将其与密文一起发送。通常,它只是简单地添加到密文之前并在解密之前将其切掉。
关于java - 如何在java和node中编写精确的加密代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44438371/