使用WebCryptography API获取CryptoJS单词

时间:2017-11-23 03:50:50

标签: javascript sha1 cryptojs webcryptoapi

我正在使用Google的CryptoJS迁移功能来浏览本机WebCryptography API。

使用CryptoJS,我使用以下代码来获取SHA1哈希的单词数组

CryptoJS.SHA1('1w0g6Ixf2VHvOc+6pGBqDHItFYQ=:9590467').words

然后返回[888149035, -1762573935, 1178769020, -1914057363, 481296384]

使用WebCrypto API,我使用

const msgBuffer = new TextEncoder().encode('1w0g6Ixf2VHvOc+6pGBqDHItFYQ=:9590467')
const hashBuffer = await crypto.subtle.digest('SHA-1', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));

hashArray[52, 240, 20, 43, 150, 241, 65, 145, 70, 66, 150, 124, 141, 233, 205, 109, 28, 176, 0, 0]

如何将此结果转换为与CyptoJS相同的数组?

1 个答案:

答案 0 :(得分:3)

如果像

一样简单就好了
const msgBuffer = new TextEncoder().encode('1w0g6Ixf2VHvOc+6pGBqDHItFYQ=:9590467')
const hashBuffer = await crypto.subtle.digest('SHA-1', msgBuffer);
const hashArray = Array.from(new Int32Array(hashBuffer));

除了字节序 - 所以,它只是稍微复杂一点

async function test() {
    const msgBuffer = new TextEncoder().encode('1w0g6Ixf2VHvOc+6pGBqDHItFYQ=:9590467')
    const hashBuffer = await crypto.subtle.digest('SHA-1', msgBuffer);
    const dv = new DataView(hashBuffer);
    const hashArray = [];
    for(let i = 0; i < dv.byteLength; i+=4) {
        hashArray.push(dv.getInt32(i, false));
    }
    return hashArray;
};
test().then(console.log);