我在使用带有 Webcrypto 的 PBKDF2 时遇到问题。我想将 PBKDF2 与 SHA-1 算法一起使用。目前,我有,
const ENCODING = "utf-8";
const HMACSHA1 = {name: "HMAC", "hash" : "SHA-1"};
const PBKDF2SHA1 = {name: "PBKDF2", "hash": "SHA-1"};
// str2binb takes a string and outputs an ArrayBuffer
async function pbkdf2_generate_key_from_string(string) { // Working
return crypto.subtle.importKey(
"raw",
str2binb(string),
PBKDF2SHA1,
false,
["deriveKey", "deriveBits"],
);
}
async function pbkdf2_derive_salted_key(key, salt, iterations) { // Not working
return crypto.subtle.deriveKey(
{
"name": "PBKDF2",
"salt": salt,
"iterations": iterations,
"hash": "SHA-1",
"length": 160
},
key,
{
"name": "HMAC"
"hash": "SHA-1",
"length": 160
},
true,
[ "encrypt", "decrypt"]
);
}
但是我知道我一定是用错了,因为它是受支持的密钥派生算法,并且根据 Mozilla 的精彩文档,derivedKeyAlgorithm
支持 HMAC 以及 HMAC-SHA1。我也让它AES-GCM
相当直接地工作。
当我尝试时,我收到的错误消息,
salt = b64binb("QSXCR+Q6sek8bf92"); // ArrayBuffer
key = await pbkdf2_generate_key_from_string("pencil");
x = await pbkdf2_derive_salted_key(key, salt, 4096)
是Uncaught DOMException: Cannot create a key using the specified key usages.
注意:我了解不再推荐使用 SHA1,这是为了支持旧版。
注意2:当我将上面的内容替换为时,它可以工作,
async function pbkdf2_derive_salted_key(key, data, salt, iterations) { // Not working
return crypto.subtle.deriveKey(
{
"name": "PBKDF2",
salt: salt,
"iterations": iterations,
"hash": "SHA-1",
},
key,
{
"name": "AES-GCM",
"length": 256
},
true,
[ "encrypt", "decrypt"]
);
}
谢谢你。