解密
decrypt()
方法解密某些加密数据。
用法
decrypt(algorithm, key, data)
参数
名称 | 类型 | 描述 |
---|---|---|
algorithm | AesCbcParams、AesCtrParams 或 AesGcmParams 对象 | 定义要使用的算法和任何额外参数。额外参数的值必须与相应的 [encrypt] 调用中使用的值匹配。 |
key | CryptoKey | 用于解密的 key。 |
data | ArrayBuffer 、TypedArray 或 DataView | 要解密的加密数据(也称为密文)。 |
支持的算法
AES-CBC | AES-CTR | AES-GCM | RSA-OAEP |
---|---|---|---|
✅ AesCbcParams | ✅ AesCtrParams | ✅ AesGcmParams | ✅ RsaOaepParams |
返回值
返回一个 Promise
,它解析为一个包含解密数据的新 ArrayBuffer
。
抛出
类型 | 描述 |
---|---|
InvalidAccessError | 当请求的操作对提供的 key 无效时抛出。例如,使用了无效的加密算法,或提供了与所选算法不匹配的 key。 |
OperationError | 当操作因特定于操作的原因失败时抛出。例如,算法大小无效,或在解密密文过程中发生错误。 |
示例
export default async function () {
const plaintext = stringToArrayBuffer('Hello, World!');
/**
* Generate a symmetric key using the AES-CBC algorithm.
*/
const key = await crypto.subtle.generateKey(
{
name: 'AES-CBC',
length: 256,
},
true,
['encrypt', 'decrypt']
);
/**
* Encrypt the plaintext using the AES-CBC key with
* have generated.
*/
const iv = crypto.getRandomValues(new Uint8Array(16));
const ciphertext = await crypto.subtle.encrypt(
{
name: 'AES-CBC',
iv: iv,
},
key,
plaintext
);
/**
* Decrypt the ciphertext using the same key to verify
* that the resulting plaintext is the same as the original.
*/
const deciphered = await crypto.subtle.decrypt(
{
name: 'AES-CBC',
iv: iv,
},
key,
ciphertext
);
console.log(
'deciphered text == original plaintext: ',
arrayBufferToHex(deciphered) === arrayBufferToHex(plaintext)
);
}
function arrayBufferToHex(buffer) {
return [...new Uint8Array(buffer)].map((x) => x.toString(16).padStart(2, '0')).join('');
}
function stringToArrayBuffer(str) {
const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
const bufView = new Uint16Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}