Web Crypto
subtle.encrypt()
Encrypts with an allowed key and algorithm. For AES-GCM use a unique IV per key, store the IV with ciphertext, and never reuse it. This lab creates a fresh key and random IV. Tested on Node.js 22.16.0. Example output (one line per entry): ["true", "book"].
Formal Syntax & Structure
nodejs syntaxnodejs
subtle.encrypt(algorithm, key, data)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| algorithm | object | Encryption parameters. |
| key | CryptoKey | Encryption key. |
| data | BufferSource | Plaintext bytes. |
Return Value
Promise<ArrayBuffer>
Ciphertext bytes.
Working Example
Example Snippetnodejs
import { webcrypto as crypto } from 'node:crypto';const k = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);const iv = crypto.getRandomValues(new Uint8Array(12));const p = new TextEncoder().encode('book');const c = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, k, p);console.log(c.byteLength > p.byteLength);console.log(new TextDecoder().decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, k, c)));