首页 > 解决方案 > crypto.subtle.deriveKey 总是返回 undefined

问题描述

这个问题的背景如下 - 我正在用 C# 在服务器上生成一些加密数据,使用密码来加密数据。我现在正在尝试使用 WebCrypto API 在客户端上解密,但是对 derivedKey 的调用总是返回 undefined(没有错误)。我尝试按如下方式创建 MCVE:

window.crypto.subtle.importKey(
    'raw',
    new TextEncoder().encode('passphrase'),
    { 
        'name': 'PBKDF2' 
    },
    false,
    ['deriveBits', 'deriveKey']
)
.then((baseKey) => {
    console.dir(baseKey) // This looks ok!
    window.crypto.subtle.deriveKey({
            'name': 'PBKDF2',
            salt: new TextEncoder().encode('my_salt'),
            iterations: 100000,
            hash: 'SHA-256'
        },
        baseKey,
        { 
            'name': 'AES-GCM', 
            iv: new TextEncoder().encode('iv_from_server'), 
            length: 256 
        },
        true,
        ['decrypt'])
})
.then((key2) => {
    console.log('generated new key')
    console.dir(key2) // This is always undefined
})
.catch((error) => console.dir(error))

我试过摆弄一些参数无济于事。它确实需要使用 PBKDF2 和 AES-GCM 来匹配服务器。我不知道我是否正在尝试做那些算法不支持的事情,或者我是否有其他错误......

标签: javascriptwebcrypto-api

解决方案


你变得不确定,因为你没有从之前的承诺中返回任何东西。如果您在调用 derivedKey 之前返回,它将解决您的问题。这是您的修复代码:

window.crypto.subtle.importKey(
    'raw',
    new TextEncoder().encode('passphrase'),
    { 
        'name': 'PBKDF2' 
    },
    false,
    ['deriveBits', 'deriveKey']
)
.then((baseKey) => {
    console.dir(baseKey) // This looks ok!

    // ADD A RETURN TO RESOLVE WITH THE KEY IN THE NEXT PROMISE:
    return window.crypto.subtle.deriveKey({
            'name': 'PBKDF2',
            salt: new TextEncoder().encode('my_salt'),
            iterations: 100000,
            hash: 'SHA-256'
        },
        baseKey,
        { 
            'name': 'AES-GCM', 
            iv: new TextEncoder().encode('iv_from_server'), 
            length: 256 
        },
        true,
        ['decrypt'])
})
.then((key2) => {
    console.log('generated new key')
    console.dir(key2) // NOW IT WORKS
})
.catch((error) => console.dir(error))

推荐阅读