javascript - 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 来匹配服务器。我不知道我是否正在尝试做那些算法不支持的事情,或者我是否有其他错误......
解决方案
你变得不确定,因为你没有从之前的承诺中返回任何东西。如果您在调用 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))
推荐阅读
- css - 连续列之间的响应文本
- assembly - 用汇编语言解释标志如何在条件跳转中工作
- python - ValueError:使用管道拟合模型时解包的值太多(预期为 3)
- google-apps-script - 为什么日期不同保存到变量不同
- python-3.x - 如何将CSV文件解析成字典并一一使用(不使用CSV库)
- javascript - IOS ontouchstart 打不开文件对话框?
- ajax - FOSJsRouting Bundle“路由不存在”
- html - 在引导程序中实现卡顶部的按钮
- javascript - 猫鼬:人口众多
- python - 数据框中列上的 .map 的 NaN 错误