【问题标题】:convert crypto.subtle.deriveKey result to hex string将 crypto.subtle.deriveKey 结果转换为十六进制字符串
【发布时间】:2018-11-10 11:24:29
【问题描述】:

根据bip39 standard,我想从javascript中的助记词中获取seed

我使用这个代码:

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 转换为其对应的种子为十六进制字符串?

【问题讨论】:

    标签: javascript cryptography


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 2018-01-22
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      • 2016-01-17
      相关资源
      最近更新 更多