SubtleCrypto.decrypt()

SubtleCrypto.decrypt() 以加密数据、算法和密钥为参数返回一个包含明文的 Promise 对象。

语法

var result = crypto.subtle.decrypt(algorithm, key, data);

属性

返回值

异常

Promise 将会在以下的异常被触发时返回 rejected:

InvalidAccessError
当提供的密钥无法执行请求的操作时(如:解密算法无效,或对指定的解密算法提供了无效的密钥)。
OperationError
因特定的操作原因导致操作失败时(如:算法的参数大小无效,或解密结果失败)。

实例

const decryptText = async (ctBuffer, iv, password) => {
    const pwUtf8 = new TextEncoder().encode(password);
    const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8);

    const alg = { name: 'AES-GCM', iv: iv };
    const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['decrypt']);

    const ptBuffer = await crypto.subtle.decrypt(alg, key, ctBuffer);

    const plaintext = new TextDecoder().decode(ptBuffer);

    return plaintext;
}

iv 的含义在 SubtleCrypto.encrypt() 中可以找到。ctBuffer 是 SubtleCrypto.encrypt() 返回的密文。

规范

Specification Status Comment
Web Cryptography API
SubtleCrypto.decrypt()
Recommendation Initial definition.

浏览器支持

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
decryptChrome Full support 37Edge Partial support 12
Notes
Partial support 12
Notes
Notes Not supported: AES-CTR.
Firefox Full support 34
Full support 34
No support 32 — 34
Disabled
Disabled From version 32 until version 34 (exclusive): this feature is behind the dom.webcrypto.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
IE Partial support 11
Notes
Partial support 11
Notes
Notes Returns CryptoOperation instead of Promise
Opera Full support 24Safari Full support 7WebView Android Full support 37Chrome Android Full support 37Firefox Android Full support 34
Full support 34
No support 32 — 34
Disabled
Disabled From version 32 until version 34 (exclusive): this feature is behind the dom.webcrypto.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
Opera Android Full support 24Safari iOS Full support 7Samsung Internet Android Full support 6.0

Legend

Full support  
Full support
Partial support  
Partial support
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.

另请参见