SubtleCrypto.decrypt()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

安全上下文: 此项功能仅在一些支持的浏览器安全上下文(HTTPS)中可用。

SubtleCrypto 接口的 decrypt() 方法用于解密加密数据。它以用于解密的密钥、一些可选的额外参数,以及待解密的数据(也称为“密文”)为参数;返回一个 Promise,会兑现解密后的数据(也称为“明文”)。

语法

js
decrypt(algorithm, key, data)

参数

algorithm

一个对象,用于指定使用的算法,以及任何需要的额外参数。额外提供的参数的值必须与对应的 encrypt() 调用所传入的值相匹配。

key

一个包含了密钥的 CryptoKey 对象,用于解密。

data

一个包含了待解密的数据(也称为密文)的 ArrayBufferTypedArrayDataView 对象。

返回值

一个 Promise,会兑现一个包含明文的 ArrayBuffer

异常

当遇到以下异常时,promise 将会被拒绝:

InvalidAccessError DOMException

当提供的密钥无法执行请求的操作时(如:解密算法无效,或对指定的解密算法提供了无效的密钥)。

OperationError DOMException

因特定的操作原因导致操作失败时(如:算法的参数大小无效,或解密密文时发生的错误)。

支持的算法

decrypt() 方法支持的算法与 encrypt() 方法所支持的相同。

示例

备注: 你可以在 GitHub 上尝试这个可用的示例

RSA-OAEP

以下代码使用 RSA-OAEP 解密 ciphertext在 GitHub 中查看完整的代码。

js
function decryptMessage(privateKey, ciphertext) {
  return window.crypto.subtle.decrypt(
    { name: "RSA-OAEP" },
    privateKey,
    ciphertext,
  );
}

AES-CTR

以下代码使用计数器(CTR)模式的 AES 解密 ciphertext。请注意,counter 必须与加密时使用的值相匹配。在 GitHub 中查看完整的代码。

js
function decryptMessage(key, ciphertext) {
  return window.crypto.subtle.decrypt(
    { name: "AES-CTR", counter, length: 64 },
    key,
    ciphertext,
  );
}

AES-CBC

以下代码使用密码块链接(CBC)模式的 AES 解密 ciphertext。请注意,iv 必须与加密时使用的值相匹配。在 GitHub 中查看完整的代码。

js
function decryptMessage(key, ciphertext) {
  return window.crypto.subtle.decrypt({ name: "AES-CBC", iv }, key, ciphertext);
}

AES-GCM

以下代码使用伽罗瓦/计数器(GCM)模式的 AES 解密 ciphertext。请注意,iv 必须与加密时使用的值相匹配。在 GitHub 中查看完整的代码。

js
function decryptMessage(key, ciphertext) {
  return window.crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ciphertext);
}

规范

Specification
Web Cryptography API
# SubtleCrypto-method-decrypt

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
decrypt

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
Has more compatibility info.

参见