files/en-us/web/api/subtlecrypto/decrypt/index.md
{{APIRef("Web Crypto API")}}{{SecureContext_header}}{{AvailableInWorkers}}
The decrypt() method of the {{domxref("SubtleCrypto")}} interface decrypts some encrypted data.
It takes as arguments a {{glossary("key")}} to decrypt with, some optional extra parameters, and the data to decrypt (also known as "ciphertext").
It returns a {{jsxref("Promise")}} which will be fulfilled with the decrypted data (also known as "plaintext").
decrypt(algorithm, key, data)
algorithm
key
privateKey property of the {{domxref("CryptoKeyPair")}} object.data
A {{jsxref("Promise")}} that fulfills with an {{jsxref("ArrayBuffer")}} containing the plaintext.
The promise is rejected when the following exceptions are encountered:
InvalidAccessError {{domxref("DOMException")}}
OperationError {{domxref("DOMException")}}
The decrypt() method supports the same algorithms as the encrypt() method.
[!NOTE] You can try the working examples on GitHub.
This code decrypts ciphertext using RSA-OAEP. See the complete code on GitHub.
function decryptMessage(privateKey, ciphertext) {
return window.crypto.subtle.decrypt(
{ name: "RSA-OAEP" },
privateKey,
ciphertext,
);
}
This code decrypts ciphertext using AES in CTR mode.
Note that counter must match the value that was used for encryption. See the complete code on GitHub.
function decryptMessage(key, ciphertext) {
return window.crypto.subtle.decrypt(
{ name: "AES-CTR", counter, length: 64 },
key,
ciphertext,
);
}
This code decrypts ciphertext using AES in CBC mode. Note that
iv must match the value that was used for encryption. See the complete code on GitHub.
function decryptMessage(key, ciphertext) {
// The iv value is the same as that used for encryption
return window.crypto.subtle.decrypt({ name: "AES-CBC", iv }, key, ciphertext);
}
This code decrypts ciphertext using AES in GCM mode. Note that
iv must match the value that was used for encryption. See the complete code on GitHub.
function decryptMessage(key, ciphertext) {
// The iv value is the same as that used for encryption
return window.crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ciphertext);
}
{{Specifications}}
{{Compat}}