[英]the output of "crypto.createCipheriv with chinese character" is not correct
when there is no chinese character, php and node output the same result.当没有汉字时,php和node输出相同的结果。
but when this is chinese character, the output of php is correct, the output of node is not correct但是当这是汉字时,php的输出是正确的,node的输出是不正确的
const crypto = require('crypto');
function encodeDesECB(textToEncode, keyString) {
var key = new Buffer(keyString.substring(0, 8), 'utf8');
var cipher = crypto.createCipheriv('des-ecb', key, '');
cipher.setAutoPadding(true);
var c = cipher.update(textToEncode, 'utf8', 'base64');
c += cipher.final('base64');
return c;
}
console.log(encodeDesECB(`{"key":"test"}`, 'MIGfMA0G'))
console.log(encodeDesECB(`{"key":"测试"}`, 'MIGfMA0G'))
6RQdIBxccCUFE+cXPODJzg==
6RQdIBxccCWXTmivfit9AOfoJRziuDf4
6RQdIBxccCUFE+cXPODJzg==
6RQdIBxccCXFCRVbubGaolfSr4q5iUgw
The problem is not the encryption, but a different JSON serialization of the plaintext.问题不在于加密,而在于明文的不同 JSON 序列化。
In the PHP code, json_encode()
converts the characters as a Unicode escape sequence, ie the encoding returns {"key":"\测\试"}
.在 PHP 代码中,
json_encode()
将字符转换为 Unicode 转义序列,即编码返回{"key":"\测\试"}
。 In the NodeJS code, however, {"key": "测试"}
is applied.但是,在 NodeJS 代码中,应用了
{"key": "测试"}
。
This means that different plaintexts are encrypted in the end.这意味着最终加密不同的明文。 Therefore, for the same ciphertext, a byte-level identical plaintext must be used.
因此,对于相同的密文,必须使用字节级别的相同明文。
If Unicode escape sequences are to be applied in the NodeJS code (as in the PHP code), an appropriate conversion is necessary.如果要在 NodeJS 代码中应用 Unicode 转义序列(如在 PHP 代码中),则需要进行适当的转换。 For this the jsesc package can be used:
为此,可以使用jsesc包:
const jsesc = require('jsesc');
...
console.log(encodeDesECB(jsesc(`{\"key\":\"测试\"}`, {'lowercaseHex': true}), 'MIGfMA0G')); // 6RQdIBxccCXFCRVbubGaolfSr4q5iUgw
now returns the result of the posted PHP code.现在返回已发布的 PHP 代码的结果。
If the Unicode characters are to be used unmasked in the PHP code (as in the NodeJS code), an appropriate conversion is necessary.如果要在 PHP 代码中不加掩码地使用 Unicode 字符(如在 NodeJS 代码中),则需要进行适当的转换。 For this the flag
JSON_UNESCAPED_UNICODE
can be set in json_encode()
:为此,可以在
json_encode()
设置标志JSON_UNESCAPED_UNICODE
:
$data = json_encode($data, JSON_UNESCAPED_UNICODE); // 6RQdIBxccCWXTmivfit9AOfoJRziuDf4
now returns the result of the posted NodeJS code.现在返回发布的 NodeJS 代码的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.