saeid ezzati
saeid ezzati

Reputation: 891

convert crypto.subtle.deriveKey result to hex string

according to bip39 standard, I want to get seed from mnemonic words in javascript.

I use this code:

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

        });
    });

}

but at last result of console.log('derivedKey: '+derivedKey); is this:

derivedKey: [object CryptoKey]

now how convert derivedKey to its corresponding seed as hex string ?

Upvotes: 5

Views: 1107

Answers (1)

saeid ezzati
saeid ezzati

Reputation: 891

finally I found that with crypto.subtle.exportKey I can get result of CryptoKey as 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;
}

Upvotes: 2

Related Questions