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

sae*_*ati 5 javascript cryptography

根据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);

        });
    });

}
Run Code Online (Sandbox Code Playgroud)

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

derivedKey: [object CryptoKey]
Run Code Online (Sandbox Code Playgroud)

现在如何将衍生密钥转换为其相应的种子作为十六进制字符串?

sae*_*ati 2

最后我发现我可以得到ascrypto.subtle.exportKey的结果CryptoKeyArrayBuffer

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;
}
Run Code Online (Sandbox Code Playgroud)