如何在java和node中编写精确的加密代码?
我需要用Java翻译以下代码:如何在java和node中编写精确的加密代码?,java,node.js,encryption,Java,Node.js,Encryption,我需要用Java翻译以下代码: public static String encode(String chave, final String value) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingExcep
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));
}
到节点。我正在努力:
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.createCipheriv
。后者使用密码而不是密钥,并使用OpenSSL的EVP_BytesToKey从中派生密钥和IV
另一个问题是您应该使用正确长度的IV:var IV=Buffer.alloc(16)代码>
其他问题可能是到处都是的编码:
value.getBytes()
使用默认的字符编码,并且每台机器的代码可能不同。始终定义特定的字符编码,如:value.getBytes(“UTF-8”)
cipher.update(data,“binary”)
假设data
是拉丁文编码的,与Java代码不匹配。使用cipher.update(数据,“utf-8”)
decodeKey=新缓冲区(键,“utf-8”)代码>看起来很糟糕,因为应该随机选择键。密钥的二进制表示通常不会产生有效的UTF-8编码。记住,密钥不是密码
安全考虑:
静脉注射必须是不可预测的(阅读:随机)。不要使用静态IV,因为这会使密码具有确定性,因此在语义上不安全。观察密文的攻击者可以确定以前何时发送相同的消息前缀。IV不是秘密,所以你可以把它和密文一起发送。通常,它只是在密文前面加上前缀,并在解密之前切掉。为什么要有相同的输出?这将是一个很好的做法,使用随机静脉注射。