哈希算法节点js与Python

时间:2017-09-02 15:35:52

标签: python node.js algorithm hash

我试图将在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])) 

生成的令牌为32d86f00-eb49-2739-e957-91513d2b9969

此处使用struct.pack生成日期值datetime值,但为方便起见,我在此处进行了硬编码。

我尝试通过查看相应库的python doc来转换它,并且到目前为止

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部分的东西。

你能指导我出错的地方吗?谢谢你的帮助

2 个答案:

答案 0 :(得分:2)

有很多错过的部分实际上已经过了调整。

节点部分:

  • new Buffer('c5')

    不代表<Buffer c5>,而是<Buffer 63 35>

    要编写c5,您需要使用Buffer.from([0xc5])Buffer.from([197])(dec)。

  • new Buffer(2)

    不代表<Buffer 02>,它只分配2个字节。

  • CLIENT_ID+SECRET+y+m+d

    缓冲区的连接不起作用。

    使用缓冲区数组和Buffer.concat([buffers])来连接缓冲区。

uuid部分:

  • 原来,uuid运行修改后的缓冲区版本(bytes_le部分在python代码中)

最有趣的部分:

  • 在uuid的python版本中,如果没有将版本参数传递给uuid.UUID(...),uuid将生成一个没有固定位的ID

    根据RFC-4122 4.4 uuid should fix that bits

    uuid.py skips RFC-4122 4.4

    node-uuid/v4.js fixes required bits

    即使sha256散列的结果相同,python和节点实现之间的结果仍然会有所不同

    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项目中的源代码,我想有一个选项来分叉uuid并删除node-uuid/v4.js中的两行代码?

请参阅以下代码的节点版本:

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;
}

答案 1 :(得分:-1)

您是否希望数据的散列与上面的Python代码相同? 如果没有,您可以查看NodeJS下面的Sha256模块

https://www.npmjs.com/package/sha256