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

时间:2018-11-10 11:24:30

标签: javascript cryptography

根据bip39 standard,我想从 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 个答案:

答案 0 :(得分:0)

最后我发现,使用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;
}