gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:20:50 25 4
gpt4 key购买 nike

根据 bip39 standard ,我想从 javascript 中的mnemonic words 中获取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 转换为对应的种子作为十六进制字符串?

最佳答案

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

关于javascript - 将 crypto.subtle.deriveKey 结果转换为十六进制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53238462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com