我试图将用 Python 编写的哈希算法转换为 node.js
python代码看起来像
import uuid
import hashlib
import struct
CLIENT_ID = uuid.UUID('c5f92e0d-e762-32cd-98cb-8c546c410dbe')
SECRET = uuid.UUID('2cf26ff5-bd06-3245-becf-4d5a3baa704f')
data = CLIENT_ID.bytes_le + SECRET.bytes_le + struct.pack("I", 2017) + struct.pack("I", 9) + struct.pack("I", 2)
token = str(uuid.UUID(bytes_le=hashlib.sha256(data).digest()[0:16]))
生成的 token 是32d86f00-eb49-2739-e957-91513d2b9969
这里的日期值 struct.pack
值是使用 datetime
生成的,但为了方便,我在这里进行了硬编码。
我试图通过查看各个库的 python 文档来转换相同的内容,并且到目前为止已经做到了
let CLIENT_ID = new Buffer('c5f92e0d-e762-32cd-98cb-8c546c410dbe');
let SECRET = new Buffer('2cf26ff5-bd06-3245-becf-4d5a3baa704f');
let d = new Buffer(2);
let m = new Buffer(9);
let y = new Buffer(2017);
let data = CLIENT_ID+SECRET+y+m+d;
const uuidv4 = require('uuid/v4');
const hash = crypto.createHash('sha256');
let token = uuidv4({random: hash.update(data, 'utf8').digest().slice(0, 16)}, 0);
它生成的哈希是 b7b82474-eab4-4295-8318-cc258577ff9b
所以,基本上我在 nodejs 部分严重遗漏了一些东西。
能否请您指导我哪里出了问题。感谢您的帮助
最佳答案
实际上它调整了很多遗漏的部分。
### Node 部分:
new Buffer('c5')
不代表
<Buffer c5>
,但是<Buffer 63 35>
.要编写 c5,您需要使用
Buffer.from([0xc5])
或Buffer.from([197])
(十二月)。new Buffer(2)
不代表
<Buffer 02>
,它只分配 2 个字节。CLIENT_ID+SECRET+y+m+d
缓冲区的连接不是那样工作的。
使用缓冲区数组和
Buffer.concat([buffers])
连接缓冲区。
###uuid 部分:
- 事实证明 uuid 操作缓冲区的修改版本(python 代码中的
bytes_le
部分)
#最有趣的部分:
在 uuid 的 python 版本中,如果没有版本参数传递给
uuid.UUID(...)
, uuid 会生成一个没有固定位的 ID根据 RFC-4122 4.4 uuid should fix that bits .
node-uuid/v4.js fixes required bits
这样即使 sha256 哈希的结果相同,python 和 Node 实现之间的结果仍然不同
python: 32d86f00-eb49-2739-e957-91513d2b9969 node: 32d86f00-eb49-4739-a957-91513d2b9969 ^ ^
所以,我在这里看到 2 个选项
- 将版本传递给 python uuid(仅针对最后一个 uuid 调用 uuid.UUID(bytes_le=..., version=4)),这样 python 将返回
32d86f00-eb49-4739-a957-91513d2b9969
- 如果无法更改 python 项目中的源代码,我想可以选择 fork uuid 并删除
node-uuid/v4.js
中的两行代码?
##请查看下面代码的 Node 版本:
const uuidv4 = require('uuid/v4');
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
const client_id_hex_str = "c5f92e0d-e762-32cd-98cb-8c546c410dbe".replace(/-/g, "");
const secret_hex_str = "2cf26ff5-bd06-3245-becf-4d5a3baa704f".replace(/-/g, "");
let CLIENT_ID = Buffer.from(to_bytes_le(to_bytes(client_id_hex_str, null, 16, 'big')));
let SECRET = Buffer.from(to_bytes_le(to_bytes(secret_hex_str, null, 16, 'big')));
let d = Buffer.from(to_bytes(null, 2, 4));
let m = Buffer.from(to_bytes(null, 9, 4));
let y = Buffer.from(to_bytes(null, 2017, 4));
let data = Buffer.concat([CLIENT_ID, SECRET, y, m, d]);
let hashBytes = hash.update(data, 'utf8').digest().slice(0, 16);
hashBytes = [].slice.call(hashBytes, 0);
hashBytes = Buffer.from(to_bytes_le(hashBytes));
let token = uuidv4({random: hashBytes});
console.log(token);
// https://stackoverflow.com/questions/16022556/has-python-3-to-bytes-been-back-ported-to-python-2-7
function to_bytes(hexString, number, length, endianess) {
if (hexString == null && number == null) {
throw new Error("Missing hex string or number.");
}
if (!length || isNaN(length)) {
throw new Error("Missing or invalid bytes array length number.");
}
if (hexString && typeof hexString != "string") {
throw new Error("Invalid format for hex value.");
}
if (hexString == null) {
if (isNaN(number)) {
throw new Error("Invalid number.");
}
hexString = number.toString(16);
}
let byteArray = [];
if (hexString.length % 2 !== 0) {
hexString = '0' + hexString;
}
const bitsLength = length * 2
hexString = ("0".repeat(bitsLength) + hexString).slice(-1 * bitsLength);
for (let i = 0; i < hexString.length; i += 2) {
const byte = hexString[i] + hexString[i + 1];
byteArray.push(parseInt(byte, 16));
}
if (endianess !== "big") {
byteArray = byteArray.reverse();
}
return byteArray;
}
// https://github.com/python/cpython/blob/master/Lib/uuid.py#L258
function to_bytes_le(bytes) {
const p1 = bytes.slice(0, 4).reverse();
const p2 = bytes.slice(4, 6).reverse();
const p3 = bytes.slice(6, 8).reverse();
const p4 = bytes.slice(8);
const bytes_le = [].concat.apply([], [p1, p2, p3, p4]);
return bytes_le;
}
关于python - 哈希算法 Node js vs Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46015397/