将crypto.subtle.deriveKey的结果转换为十六进制字符串

5
根据bip39标准,我想在JavaScript中从助记词中获取种子
我使用以下代码:
function mnemonicToSeed(mnemonic,passphrase){
    if (typeof passphrase != 'string') passphrase='';

    window.crypto.subtle.importKey(
        'raw',
        stringToArrayBuffer(mnemonic),
        {
            name: 'PBKDF2',
        },
        false,
        ['deriveKey']
    ).then((importedKey) => {

        crypto.subtle.deriveKey({
                name: "PBKDF2",
                salt: stringToArrayBuffer('mnemonic'+passphrase),
                iterations: 2048,
                hash: { name: 'SHA-512' }
            }, 
            importedKey,
            {
                name: 'HMAC',
                hash: 'SHA-512',
                length: 512
            },
            true,
            ['sign']
        ).then(function(derivedKey) {
            console.log('derivedKey: '+derivedKey);

        });
    });

}

但是最后console.log('derivedKey: '+derivedKey);的结果是这样的:

derivedKey: [object CryptoKey]

现在如何将derivedKey转换为相应的十六进制字符串种子?

1个回答

2

最后我发现使用 crypto.subtle.exportKey 可以将 CryptoKey 的结果作为 ArrayBuffer 获取

window.crypto.subtle.importKey(
    'raw',
    stringToArrayBuffer(mnemonic),
    {
        name: 'PBKDF2',
    },
    false,
    ['deriveKey']
).then((importedKey) => {

    crypto.subtle.deriveKey({
            name: "PBKDF2",
            salt: stringToArrayBuffer('mnemonic'+passphrase),
            iterations: 2048,
            hash: { name: 'SHA-512' }
        }, 
        importedKey,
        {
            name: 'HMAC',
            hash: 'SHA-512',
            length: 512
        },
        true,
        ['sign']
    ).then(function(derivedKey) {

        crypto.subtle.exportKey('raw',derivedKey).then((exportedKey) => {
            console.log(convertArrayBufferToHexaDecimal(exportedKey));
        });

    });
})

function convertArrayBufferToHexaDecimal(buffer) 
{
    var data_view = new DataView(buffer)
    var iii, len, hex = '', c;

    for(iii = 0, len = data_view.byteLength; iii < len; iii += 1) 
    {
        c = data_view.getUint8(iii).toString(16);
        if(c.length < 2) 
        {
            c = '0' + c;
        }

        hex += c;
    }

    return hex;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接