crypto.subtle.encrypt
Encrypts data using the specified algorithm and cryptographic key
Syntax
crypto.subtle.encrypt(algorithm, key, data)Parameters
| Parameter | Type | Description |
|---|---|---|
| algorithm | AlgorithmIdentifier | The encryption algorithm and parameters |
| key | CryptoKey | The key to use for encryption |
| data | ArrayBuffer | TypedArray | DataView | The data to encrypt |
Return Value
A Promise that resolves to an ArrayBuffer containing the ciphertext
Examples
const key = await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt']
)
const iv = crypto.getRandomValues(new Uint8Array(12))
const encoded = new TextEncoder().encode('Secret message')
const encrypted = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
encoded
)async function encryptText(text: string, key: CryptoKey) {
const iv = crypto.getRandomValues(new Uint8Array(12))
const data = new TextEncoder().encode(text)
const cipher = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, data)
return { iv, cipher }
}async function generateAndExportKey() {
const key = await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt']
)
const exported = await crypto.subtle.exportKey('jwk', key)
console.log(exported)
}Understanding crypto.subtle.encrypt
The crypto.subtle.encrypt method in JavaScript encrypts data using the specified algorithm and cryptographic key. It belongs to the SubtleCrypto object and is one of the most widely used methods for working with subtlecrypto values in modern JavaScript and TypeScript applications.
The method signature is crypto.subtle.encrypt(algorithm, key, data). It accepts 3 parameters: algorithm, key, data. When called, it returns a promise that resolves to an arraybuffer containing the ciphertext. Understanding when and how to use encrypt() helps you write more expressive, readable code.
Common use cases for crypto.subtle.encrypt include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like crypto-subtle-decrypt, crypto-subtle-digest, crypto-getrandomvalues, enabling you to chain operations together for complex data manipulation pipelines.
Supported in all modern browsers. Requires a secure context (HTTPS).
Browser Compatibility
Supported in all modern browsers. Requires a secure context (HTTPS).
Related Methods
More SubtleCrypto Methods
Other methods in the SubtleCrypto object
Related Tools
More SubtleCrypto Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.