我正在尝试使用SubtleCrypto加密字符串、存储加密字符串并再次解密该字符串,所有这些都使用生成的 RSA-OAEP 密钥对。
下面的代码在解密阶段会产生一个 DOMException,但是我似乎无法获得有关该错误的任何详细信息。我尝试使用“SHA-1”进行散列,但有同样的问题。
有什么提示吗?
let encoder = new TextEncoder();
let decoder = new TextDecoder('utf-8');
// Generate a key pair
let keyPair = await window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 4096,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256"
},
true,
["encrypt", "decrypt"]
);
let publicKey = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
let privateKey = await crypto.subtle.exportKey('jwk', keyPair.privateKey);
// Encrypt a string
let encodedSecret = encoder.encode("MYSECRETVALUE");
let pubcryptokey = await window.crypto.subtle.importKey(
'jwk',
publicKey,
{
name: "RSA-OAEP",
hash: "SHA-256"
},
false,
["encrypt"]
);
let encrypted = await window.crypto.subtle.encrypt(
{
name: "RSA-OAEP"
},
pubcryptokey,
encodedSecret
);
let encDV = new DataView(encrypted);
let ct = decoder.decode(encDV);
// Decrypt the string
let encodedCiphertext = encoder.encode(ct);
let privcryptokey = await window.crypto.subtle.importKey(
'jwk',
privateKey,
{
name: "RSA-OAEP",
hash: "SHA-256"
},
false,
["decrypt"]
);
console.log("Before decrypt");
let decrypted = await window.crypto.subtle.decrypt(
{
name: "RSA-OAEP"
},
privcryptokey,
encodedCiphertext
);
console.log("After decrypt");
let decDV = new DataView(decrypted);
let pt = decoder.decode(decDV);
console.log(pt);