encrypt(): Promise<string>
Encrypt message with key.
It returns an hexadecimal string structured as follows:
┌──────────────────────┬─────────────────┬────────────┬───────────┬────────────┬╴╴╴╴╴╴╴╴╴╴╴╴╴╴┐ │ Initial Vector [16b] │ Signature [16b] │ Hash [64b] │ Size [8b] │ Value [Xb] │ Padding [Yb] ┊ └──────────────────────┴─────────────────┴────────────┴───────────┴────────────┴╴╴╴╴╴╴╴╴╴╴╴╴╴╴┘
The following are used by the native SubtleCrypto.encrypt API:
- The initial vector (IV) is used by AES-GCM algorithm to ensure a same input will yield different outputs each time and prevent stream cipher attacks.
- The signature is used by the AES-GCM algorithm internally
The following are used by this library:
- The hash (SHA-256) is used to ensure the integrity of the size and value after decryption, while providing extra entropy
- The size is the length of the secret value in bits, which is used to discard the padding after decryption
- The value is the actual secret
- The padding is used to obfuscate the actual value length, while providing extra entropy
The length parameter is used to specify the length of the output hash in bits.
Supported values are 256 and 512.
If set to 0 instead, padding will be disabled entirely allowing to encrypt larger values but at the cost of leaking the approximate values length.
Additionally, if a value size exceed 255 bytes, its integrity will only be checked by the hash field.
import { decrypt, encrypt, exportKey } from "./encryption.ts" const key = await exportKey({ seed: "", salt: "" }) console.assert(await decrypt(await encrypt("🍱 bento", { key }), { key }) === "🍱 bento")