从'crypto'迁移到crypto-js库:二进制编码

时间:2018-09-26 18:07:31

标签: node.js cryptojs node-crypto

我正在尝试在不幸的是不支持标准Node crypto库的设备上生成SHA256和HmacSHA512哈希。因此,我正在调整代码以改为使用CryptoJS。但是,CryptoJS不能像二进制那样对哈希进行编码(只有十六进制,Base64和Latin1是可用的编码器)。

以下是我要迁移的功能。先前的(不可用的)代码已被注释掉。

const getMessageSignature = (path, request, secret, nonce) => {
    // Expected outcome:
    // API-Sign = Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
    const message = JSON.stringify(request);

    const secret_buffer = btoa(secret);
    const hash = CryptoJS.algo.SHA256.create();
    const hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secret_buffer);
    const hash_digest = hash.update(nonce + message).finalize().toString(CryptoJS.enc.Base64);
    const hmac_digest = hmac.update(path + hash_digest).finalize().toString(CryptoJS.enc.Base64);

    // CANNOT USE BELOW (Buffer and crypto not supported)
    // const secret_buffer = new Buffer(secret, 'base64');
    // const hash = new crypto.createHash('sha256');
    // const hmac = new crypto.createHmac('sha512', secret_buffer);
    // const hash_digest = hash.update(nonce + message).digest('binary');
    // const hmac_digest = hmac.update(path + hash_digest, 'binary').digest('base64');

    return hmac_digest;
};

1 个答案:

答案 0 :(得分:1)

我找到了答案。首先:this.DispatcherUnhandledException += App_DispatcherUnhandledException; 不是必需的,因为CryptoJS具有自己的功能,可以将Base64转换为自己的格式(WordLists):for($i = 0; $i < count($data); $i++) { if($data[$i][3] == 'Each week') { $data[$i][1] = date('Y-m-d', strtotime($data[$i][6] . ' +1 week')); } } 。接下来是btoa()CryptoJS.enc.Base64.parse无法正确合并,因为存在类型不匹配(字符串和二进制),因此JS使用字符串表示形式。解决方案是首先使用path创建SHA512 HMAC,然后使用hash_digest逐步更新每个值。最后,您还必须使用CryptoJS的内置Base64解码器来最终生成签名字符串。

CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA512, secret)
相关问题