Web Crypto API
SubtleCrypto 接口的 decrypt() 方法用于解密加密数据。它以用于解密的key、一些可选的额外参数,以及待解密的数据(也称为“密文”)为参数;返回一个 Promise,会兑现解密后的数据(也称为“明文”)。
语法
decrypt(algorithm, key, data)
参数
-
algorithm -
key- : 一个包含了密钥的 CryptoKey 对象,用于解密。
-
data- : 一个包含了待解密的数据(也称为ciphertext)的 ArrayBuffer、TypedArray 或 DataView 对象。
返回值
一个 Promise,会兑现一个包含明文的 ArrayBuffer。
异常
当遇到以下异常时,promise 将会被拒绝:
InvalidAccessErrorDOMException- : 当提供的密钥无法执行请求的操作时(如:解密算法无效,或对指定的解密算法提供了无效的密钥)。
OperationErrorDOMException- : 因特定的操作原因导致操作失败时(如:算法的参数大小无效,或解密密文时发生的错误)。
支持的算法
decrypt() 方法支持的算法与 encrypt() 方法所支持的相同。
示例
[!NOTE] 你可以在 GitHub 上尝试这个可用的示例。
RSA-OAEP
以下代码使用 RSA-OAEP 解密 ciphertext。在 GitHub 中查看完整的代码。
function decryptMessage(privateKey, ciphertext) {
return window.crypto.subtle.decrypt(
{ name: "RSA-OAEP" },
privateKey,
ciphertext,
);
}
AES-CTR
以下代码使用计数器(CTR)模式的 AES 解密 ciphertext。请注意,counter 必须与加密时使用的值相匹配。在 GitHub 中查看完整的代码。
function decryptMessage(key, ciphertext) {
return window.crypto.subtle.decrypt(
{ name: "AES-CTR", counter, length: 64 },
key,
ciphertext,
);
}
AES-CBC
以下代码使用密码块链接(CBC)模式的 AES 解密 ciphertext。请注意,iv 必须与加密时使用的值相匹配。在 GitHub 中查看完整的代码。
function decryptMessage(key, ciphertext) {
return window.crypto.subtle.decrypt({ name: "AES-CBC", iv }, key, ciphertext);
}
AES-GCM
以下代码使用伽罗瓦/计数器(GCM)模式的 AES 解密 ciphertext。请注意,iv 必须与加密时使用的值相匹配。在 GitHub 中查看完整的代码。
function decryptMessage(key, ciphertext) {
return window.crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ciphertext);
}
规范
浏览器兼容性
参见
- SubtleCrypto.encrypt()。
- RFC 3447 规定了 RSAOAEP。
- NIST SP800-38A 规定了 CTR 模式。
- NIST SP800-38A 规定了 CBC 模式。
- NIST SP800-38D 规定了 GCM 模式。
- FIPS 198-1 规定了 HMAC。
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
