Crypto - Full Reference
Exhaustive reference for AES, RSA, ECDH, the shared AbstractCryptoAlgorithm/BaseCryptoAlgorithm base classes, and Hash. For a readable introduction and the most common tasks, start with the Crypto overview.
Files:
packages/helpers/src/modules/crypto/algorithms/abstract.algorithm.ts-AbstractCryptoAlgorithmpackages/helpers/src/modules/crypto/algorithms/base.algorithm.ts-BaseCryptoAlgorithmpackages/helpers/src/modules/crypto/algorithms/aes.algorithm.ts-AES,AESAlgorithmTypepackages/helpers/src/modules/crypto/algorithms/rsa.algorithm.ts-RSA,RSAAlgorithmTypepackages/helpers/src/modules/crypto/algorithms/ecdh.algorithm.ts-ECDH,ECDHAlgorithmType,IECDHEncryptedPayload,IECDHExtraOptionspackages/helpers/src/modules/crypto/common/types.ts-ICryptoAlgorithmpackages/helpers/src/modules/crypto/common/constants.ts-DEFAULT_CIPHER_BITS,DEFAULT_KDF_SALT,DEFAULT_KDF_ITERATIONS,DEFAULT_KDF_DIGEST,MINIMUM_KDF_SALT_BYTES,MINIMUM_RSA_MODULUS_BITS,HashAlgorithms,HashOutputEncodingspackages/helpers/src/modules/crypto/algorithms/hash.algorithm.ts-Hash
Quick Reference
| Class | Extends | Secret type | Async | Runtime API |
|---|---|---|---|---|
AES | BaseCryptoAlgorithm | TAESSecret - string | IAESKeyringEntry[] | Yes | Web Crypto (crypto.subtle) |
RSA | BaseCryptoAlgorithm | string (base64 DER key) | Yes | Web Crypto (crypto.subtle) |
ECDH | AbstractCryptoAlgorithm | CryptoKey | Yes | Web Crypto (crypto.subtle) |
Hash | BaseHelper | string (HMAC only - digest takes none) | No | Bun (Bun.CryptoHasher) |
Import paths
// Algorithm classes
import { AES, RSA, ECDH, Hash } from '@venizia/ignis-helpers';
// Hash const-classes
import { HashAlgorithms, HashOutputEncodings } from '@venizia/ignis-helpers';
// KDF and RSA constants
import {
DEFAULT_KDF_SALT,
DEFAULT_KDF_ITERATIONS,
DEFAULT_KDF_DIGEST,
MINIMUM_KDF_SALT_BYTES,
MINIMUM_RSA_MODULUS_BITS,
} from '@venizia/ignis-helpers';
// Types
import type {
AESAlgorithmType,
TAESSecret,
IAESKeyringEntry,
RSAAlgorithmType,
ECDHAlgorithmType,
IECDHEncryptedPayload,
IECDHExtraOptions,
ICryptoAlgorithm,
} from '@venizia/ignis-helpers';All of the above resolve through the root @venizia/ignis-helpers barrel, which re-exports ./modules (and therefore ./modules/crypto) and ./utilities in full.
IAESOptions is named in the signatures below, but it is not exported. Write the option object inline, or derive the shape when you need a name for it:
type TAesEncryptOptions = NonNullable<Parameters<AES['encrypt']>[0]['opts']>;Type Hierarchy
Source -> base.algorithm.ts
ICryptoAlgorithm (interface)
└── AbstractCryptoAlgorithm (extends BaseHelper)
├── BaseCryptoAlgorithm (adds normalizeSecretKey, getAlgorithmKeySize)
│ ├── AES
│ └── RSA
└── ECDH (uses CryptoKey objects, not string secrets)ICryptoAlgorithm carries 7 generic type parameters - the algorithm name literal, encrypt/decrypt input and output types, the secret key type, and an extra-options type:
interface ICryptoAlgorithm<
AlgorithmNameType extends string,
EncryptInputType = unknown,
DecryptInputType = unknown,
SecretKeyType = unknown,
EncryptReturnType = unknown,
DecryptReturnType = unknown,
ExtraOptions = unknown,
> {
algorithm: AlgorithmNameType;
encrypt(opts: { message: EncryptInputType; secret: SecretKeyType; opts?: ExtraOptions }): EncryptReturnType;
decrypt(opts: { message: DecryptInputType; secret: SecretKeyType; opts?: ExtraOptions }): DecryptReturnType;
}AbstractCryptoAlgorithm extends BaseHelper and declares encrypt/decrypt as abstract. It adds no behavior of its own, and it lives in its own file with no node:* import, so a browser-pure class can extend it (ECDH does). It is still exported from base.algorithm.ts and from the package root, and also from @venizia/ignis-helpers/core. BaseCryptoAlgorithm is the concrete base for string-secret algorithms:
| Member | Signature | Description |
|---|---|---|
| constructor | (opts: { scope: string; algorithm: AlgorithmType }) | Sets this.algorithm, calls validateAlgorithmName |
validateAlgorithmName | (opts: { algorithm: AlgorithmType }) => void | Throws if algorithm is empty/falsy |
normalizeSecretKey | (opts: { secret: string; length: number; kdfSalt?: string; kdfIterations?: number }) => Promise<Buffer> | Derives a length-byte key with PBKDF2-SHA256, 100,000 iterations. Results are memoised per secret, salt, iteration count and length |
getAlgorithmKeySize | () => number | Parses the bit size out of this.algorithm (256 from 'aes-256-gcm'), divides by 8, and returns the byte count - 32, not 256 |
normalizeSecretKey never pads and never truncates. It always runs the KDF, over crypto.subtle, and resolves to the key.
| Option | Type | Default | Meaning |
|---|---|---|---|
kdfSalt | string | DEFAULT_KDF_SALT, 'ignis-kdf-salt-v1' | Per-deployment PBKDF2 salt |
kdfIterations | number | DEFAULT_KDF_ITERATIONS, 100000 | PBKDF2 iteration count |
A kdfSalt shorter than MINIMUM_KDF_SALT_BYTES (16 bytes, the NIST SP 800-132 floor) throws [BaseCryptoAlgorithm][validateKdfSalt] kdfSalt must be at least 16 bytes, got N. A short salt looks configured while giving up most of what a salt is for, so it is refused rather than accepted quietly.
WARNING
Both values are part of the derived key. Pass the same kdfSalt and kdfIterations on decrypt that you passed on encrypt, or the key differs and the ciphertext will not open. Omit both to get the shipped defaults on both sides.
DEFAULT_KDF_SALT is public and identical in every deployment. It stops a bare dictionary attack, not a table precomputed against that exact value. Never change the constant itself: every ciphertext already written under it becomes undecryptable.
ECDH extends AbstractCryptoAlgorithm directly. It does not inherit normalizeSecretKey or getAlgorithmKeySize - its secrets are CryptoKey objects, not strings.
AES
Source -> aes.algorithm.ts
type AESAlgorithmType = 'aes-256-cbc' | 'aes-256-gcm';
const aes = AES.withAlgorithm('aes-256-gcm'); // or 'aes-256-cbc'| Mode | Authenticated | Notes |
|---|---|---|
aes-256-cbc | No | Plain block cipher, no tamper detection |
aes-256-gcm | Yes | Ciphertext includes a 16-byte GCM auth tag; tampering throws on decrypt |
encrypt
encrypt(opts: { message: string; secret: TAESSecret; opts?: IAESOptions }): Promise<string>Option (opts.opts) | Type | Default | Description |
|---|---|---|---|
inputEncoding | crypto.Encoding | 'utf-8' | Encoding of message |
outputEncoding | crypto.Encoding | 'base64' | Encoding of the returned ciphertext |
kdfSalt | string | 'ignis-kdf-salt-v1' | PBKDF2 salt. At least 16 bytes, or the call throws. Pass the same value on decrypt |
kdfIterations | number | 100000 | PBKDF2 iteration count. Pass the same value on decrypt |
The secret is run through normalizeSecretKey to the algorithm's key size (32 bytes for both modes) before being used as the cipher key. The envelope records the key id but not the salt or the iteration count, so those two are yours to keep. The output is a self-describing envelope, concatenated and encoded with outputEncoding:
[version(1)][idLen(1)][id(idLen)][iv(16)][authTag(16, gcm only)][ciphertext]The version byte is 0x01. The key id is the entry decrypt looks up in a keyring - '0' when secret is a bare string.
This envelope is not the pre-PBKDF2 one
Ciphertext written before this format started with the raw IV and derived its key by padding the secret. decrypt rejects it on its version byte; re-encrypt that data with the key you still hold.
const encrypted = await aes.encrypt({
message: 'hello',
secret: 'my-secret',
opts: {
inputEncoding: 'utf-8',
outputEncoding: 'hex',
},
});decrypt
decrypt(opts: { message: string; secret: TAESSecret; opts?: IAESOptions }): Promise<string>There is no iv option. Every encrypt draws a fresh random 16-byte IV from crypto.getRandomValues and writes it into the envelope, and decrypt reads it from there. A caller-chosen IV is how a nonce gets reused, and an IV reused under aes-256-gcm breaks confidentiality and integrity. A call to encrypt or decrypt that passes iv throws The iv option was removed. Ciphertext that was written under a fixed IV still decrypts: the IV is in the envelope.
Option (opts.opts) | Type | Default | Description |
|---|---|---|---|
inputEncoding | crypto.Encoding | 'base64' | Encoding of message |
outputEncoding | crypto.Encoding | 'utf-8' | Encoding of the returned plaintext |
kdfSalt | string | 'ignis-kdf-salt-v1' | PBKDF2 salt. Must match the value used on encrypt, and be at least 16 bytes |
kdfIterations | number | 100000 | PBKDF2 iteration count. Must match the value used on encrypt |
WARNING
A kdfSalt or kdfIterations mismatch derives a different key. Under aes-256-gcm the auth tag fails and decryption throws. Under aes-256-cbc you get a padding error or, worse, silent garbage. Store both alongside the ciphertext if they are not constants in your deployment.
For aes-256-gcm, the next 16 bytes after the IV are read as the auth tag. That tag is passed to setAuthTag before the remaining bytes are treated as ciphertext.
WARNING
Decrypting aes-256-gcm ciphertext with an aes-256-cbc instance (or vice versa) throws, and the returned Promise rejects. The two modes produce incompatible byte layouts - always encrypt and decrypt with the same one.
encryptFile / decryptFile
encryptFile(opts: { absolutePath: string; secret: TAESSecret }): Promise<string>
decryptFile(opts: { absolutePath: string; secret: TAESSecret }): Promise<string>Both read the file synchronously via fs.readFileSync, decode it as UTF-8, then await encrypt/decrypt on the string content using default extra-options. If absolutePath is empty or falsy, both resolve to '' without touching the filesystem.
Neither takes an options object, so neither can carry a custom kdfSalt or kdfIterations. Read the file yourself and call encrypt/decrypt directly when you need those.
const encrypted = await aes.encryptFile({ absolutePath: '/path/to/config.json', secret: 'my-secret' });
const decrypted = await aes.decryptFile({ absolutePath: '/path/to/config.json.enc', secret: 'my-secret' });Key rotation with a keyring
secret accepts a list as well as a string. Encryption always uses the first entry; decryption looks up the id stamped in the envelope.
const KEYRING = [
{ id: '2', secret: process.env.APP_ENV_SECRET_V2! }, // current - everything new is written with this
{ id: '1', secret: process.env.APP_ENV_SECRET_V1! }, // retired - still needed to read old rows
];
const fresh = await aes.encrypt({ message: 'payload', secret: KEYRING }); // tagged id '2'
const old = await aes.decrypt({ message: rowFromLastYear, secret: KEYRING }); // resolved by its own idRotating means prepending a new entry, not re-encrypting the estate. Drop an old entry only once nothing carries its id any more - decrypt throws No key in keyring matches ciphertext key id when it cannot resolve one, and a keyring entry with an empty secret is refused by name rather than failing later inside OpenSSL.
secret shape | Encrypts with | Envelope key id |
|---|---|---|
'my-secret' | that string | '0' |
[{ id, secret }, ...] | the FIRST entry | that entry's id |
RSA
Source -> rsa.algorithm.ts
type RSAAlgorithmType = 'rsa';
const rsa = RSA.withAlgorithm(); // no parameters - always algorithm 'rsa'generateDERKeyPair
generateDERKeyPair(opts?: { modulus: number }): Promise<{ publicKey: Buffer; privateKey: Buffer }>| Option | Type | Default | Description |
|---|---|---|---|
modulus | number | MINIMUM_RSA_MODULUS_BITS, 2048 | RSA modulus length in bits, passed to crypto.subtle.generateKey |
A modulus below MINIMUM_RSA_MODULUS_BITS throws [RSA][generateDERKeyPair] Modulus N is below the 2048-bit minimum. The key is refused rather than generated. A weak key that exists is a weak key someone will end up using. 2048 bits is the NIST SP 800-57 Part 1 floor past 2030.
publicKey is exported as { type: 'spki', format: 'der' }, privateKey as { type: 'pkcs8', format: 'der' }. Both are raw Buffers. Base64-encode them (.toString('base64')) to pass as the secret string to encrypt/decrypt.
encrypt
encrypt(opts: { message: string; secret: string; opts?: IRSAExtraOptions }): Promise<string>secret is the base64-encoded public key (SPKI/DER). It is imported with crypto.subtle.importKey('spki', ...), and the message is encrypted with crypto.subtle.encrypt under RSA-OAEP with SHA-1.
Option (opts.opts) | Type | Default | Description |
|---|---|---|---|
inputEncoding.key | crypto.Encoding | 'base64' | Encoding of the secret key buffer |
inputEncoding.message | crypto.Encoding | 'utf-8' | Encoding of message |
outputEncoding | crypto.Encoding | 'base64' | Encoding of the returned ciphertext |
decrypt
decrypt(opts: { message: string; secret: string; opts?: IRSAExtraOptions }): Promise<string>secret is the base64-encoded private key (PKCS8/DER). It is imported with crypto.subtle.importKey('pkcs8', ...), and the message is decrypted with crypto.subtle.decrypt under RSA-OAEP with SHA-1.
Option (opts.opts) | Type | Default | Description |
|---|---|---|---|
inputEncoding.key | crypto.Encoding | 'base64' | Encoding of the secret key buffer |
inputEncoding.message | crypto.Encoding | 'base64' | Encoding of message |
outputEncoding | crypto.Encoding | 'utf-8' | Encoding of the returned plaintext |
const rsa = RSA.withAlgorithm();
const { publicKey, privateKey } = await rsa.generateDERKeyPair({ modulus: 4096 });
const encrypted = await rsa.encrypt({
message: 'hello',
secret: publicKey.toString('base64'),
opts: { outputEncoding: 'hex' },
});
const decrypted = await rsa.decrypt({
message: encrypted,
secret: privateKey.toString('base64'),
opts: { inputEncoding: { key: 'base64', message: 'hex' } },
});ECDH Key Exchange
Source -> ecdh.algorithm.ts
ECDH implements ECDH P-256 key exchange with HKDF-derived AES-256-GCM session encryption, entirely on the Web Crypto API (crypto.subtle). Every method is async.
It also runs in a browser or a Worker: base64 is btoa/atob, with no Buffer and no node:*, so import it from @venizia/ignis-helpers/core and a page and a server speak one wire format with one class. The wire format is the same as before: a raw public key, a 32-byte salt, a 12-byte IV and a 128-bit tag, all base64.
const ecdh = ECDH.withAlgorithm(); // curve is always 'ecdh-p256'
const ecdhCustom = ECDH.withAlgorithm({ algorithm: 'ecdh-p256', hkdfInfo: 'my-app-session-keys' });The options argument is optional. Pass one and algorithm becomes required, even though the constructor ignores it and always sets 'ecdh-p256'.
| Constructor option | Type | Required | Description |
|---|---|---|---|
algorithm | 'ecdh-p256' | Only when you pass an options object | Accepted but not branched on - the curve is always P-256 |
hkdfInfo | string | No - defaults to 'ignis-ecdh-p256-aes-256-gcm-v1' | HKDF info string, UTF-8 encoded, used to isolate key derivation between application contexts |
Different hkdfInfo values produce incompatible derived keys from the same ECDH shared secret.
Key generation and import
| Method | Signature | Description |
|---|---|---|
generateKeyPair | () => Promise<{ keyPair: CryptoKeyPair; publicKeyB64: string }> | deriveBits-only key pair (extractable: false); publicKeyB64 is the raw exported public key, base64-encoded (65 bytes for P-256) |
importPublicKey | (opts: { rawKeyB64: string }) => Promise<CryptoKey> | Imports a peer's raw base64 public key |
const { keyPair, publicKeyB64 } = await ecdh.generateKeyPair();
const peerKey = await ecdh.importPublicKey({ rawKeyB64: peerPublicKeyB64 });deriveAESKey
deriveAESKey(opts: {
privateKey: CryptoKey;
peerPublicKey: CryptoKey;
salt?: string;
}): Promise<{ key: CryptoKey; salt: string }>Derives shared bits via ECDH (deriveBits, 256 bits) and imports them as an HKDF key. It then derives a non-extractable AES-256-GCM CryptoKey via HKDF-SHA256, using salt and the instance's hkdfInfo.
| Option | Type | Default | Description |
|---|---|---|---|
privateKey | CryptoKey | - | Caller's ECDH private key from generateKeyPair() |
peerPublicKey | CryptoKey | - | Peer's public key from importPublicKey() |
salt | string | A random 32-byte salt is generated | Base64-encoded HKDF salt. Omit to generate a new random one |
IMPORTANT
Both parties must use the same salt to derive matching keys. The initiator omits salt - a random one is generated and returned. The responder passes that returned salt back into their own deriveAESKey call. If both sides generate their own salt instead, the two keys never match.
encrypt / decrypt
encrypt(opts: { message: string; secret: CryptoKey; opts?: IECDHExtraOptions }): Promise<IECDHEncryptedPayload>
decrypt(opts: { message: IECDHEncryptedPayload; secret: CryptoKey; opts?: IECDHExtraOptions }): Promise<string>secret is the CryptoKey returned by deriveAESKey. Uses AES-GCM with a random 12-byte IV per call and a 128-bit auth tag.
interface IECDHEncryptedPayload {
iv: string; // base64 encoded 12-byte IV
ct: string; // base64 encoded ciphertext + 128-bit GCM auth tag
}
interface IECDHExtraOptions {
additionalData?: string;
}opts.additionalData (AAD) is authenticated but not encrypted. It binds the ciphertext to a context - a channel ID, a session ID - so it can't be replayed into a different one. Decrypt must supply the exact same additionalData. A mismatch throws, and so does omitting it when encrypt supplied one.
Complete flow
const ecdh = ECDH.withAlgorithm();
// 1. Both parties generate key pairs
const alice = await ecdh.generateKeyPair();
const bob = await ecdh.generateKeyPair();
// 2. Exchange public keys (safe to share over any channel)
const alicePubForBob = await ecdh.importPublicKey({ rawKeyB64: alice.publicKeyB64 });
const bobPubForAlice = await ecdh.importPublicKey({ rawKeyB64: bob.publicKeyB64 });
// 3. Initiator derives the AES key (generates a random salt)
const { key: aliceKey, salt } = await ecdh.deriveAESKey({
privateKey: alice.keyPair.privateKey,
peerPublicKey: bobPubForAlice,
});
// 4. Responder derives the SAME AES key using the initiator's salt
const { key: bobKey } = await ecdh.deriveAESKey({
privateKey: bob.keyPair.privateKey,
peerPublicKey: alicePubForBob,
salt,
});
// 5. Alice encrypts, Bob decrypts (or vice versa)
const encrypted = await ecdh.encrypt({ message: 'Hello Bob!', secret: aliceKey });
const decrypted = await ecdh.decrypt({ message: encrypted, secret: bobKey });
// => 'Hello Bob!'Security properties
| Property | Guarantee |
|---|---|
| Confidentiality | AES-256-GCM encryption |
| Integrity | GCM authentication tag - tampered ciphertext is detected on decrypt |
| Forward secrecy | Ephemeral, non-extractable key pairs - compromising one session does not compromise others |
| Key isolation | hkdfInfo separates key derivation across application contexts |
| Context binding | additionalData (AAD) prevents cross-context replay |
Hashing
Source -> hash.algorithm.ts
Hash lives in modules/crypto alongside AES/RSA/ECDH, but does not implement ICryptoAlgorithm - a digest cannot be reversed, so there is no decrypt. It extends BaseHelper directly and follows the same withAlgorithm() factory shape as the other algorithms.
class Hash extends BaseHelper {
static withAlgorithm(algorithm: THashAlgorithm): Hash;
digest(opts: { message: string | Uint8Array | ReadonlyArray<string | Uint8Array>; opts?: { outputEncoding?: THashOutputEncoding } }): string;
hmac(opts: { message: string | Uint8Array; secret: string | Uint8Array; opts?: { outputEncoding?: THashOutputEncoding } }): string;
}| Member | Signature | Description |
|---|---|---|
Hash.withAlgorithm(algorithm) | (algorithm: THashAlgorithm) => Hash | Returns a memoized instance for algorithm - at most five instances ever exist, one per algorithm |
digest | (opts: { message: string | Uint8Array | ReadonlyArray<string | Uint8Array>; opts?: IHashExtraOptions }) => string | Plain digest. Takes no secret at all. Text is hashed as UTF-8, bytes as they are, and an array is several parts hashed in order as one message |
hmac | (opts: { message: string | Uint8Array; secret: string | Uint8Array; opts?: IHashExtraOptions }) => string | Keyed HMAC. secret is required and validated non-empty in either form; throws via getError if empty. A Buffer or Uint8Array key gives the same output as the text of the same bytes |
| Const-class | Values |
|---|---|
HashAlgorithms | MD5, SHA1, SHA256, SHA384, SHA512 |
HashOutputEncodings | HEX (default), BASE64, BASE64URL |
WARNING
MD5 and SHA1 are cryptographically broken/weak. They are kept only for wire-protocol compatibility (VNPay checksums and similar); never use them for a security decision such as integrity or authenticity.
import { Hash, HashAlgorithms, HashOutputEncodings } from '@venizia/ignis-helpers';
const md5Digest = Hash.withAlgorithm(HashAlgorithms.MD5).digest({ message: 'some text' });
// outputEncoding defaults to 'hex'
const sha256Hmac = Hash.withAlgorithm(HashAlgorithms.SHA256).hmac({
message: 'some text',
secret: 'a-secret-key',
opts: { outputEncoding: HashOutputEncodings.BASE64 },
});NOTE
The old standalone hash(text, options) function is removed - see the 2026-08-30 changelog for the migration table.
Passwords
CredentialHelper is a class of static methods over Bun.password. It throws on a runtime other than Bun.
| Method | Returns | Notes |
|---|---|---|
hash({ password, algorithm?, cost? }) | Promise<string> | algorithm is 'argon2id' (default, the default parameters of Bun.password, $argon2id$) or 'bcrypt' ($2b$, 60 characters). cost is for bcrypt only: an integer from 4 to 31, default 10. An empty or non-string password, an unknown algorithm, a cost with argon2id and a cost out of range throw. A bcrypt hash written for a password longer than 72 bytes is read by Bun only, not by the bcrypt package |
verify({ password, hash }) | Promise<boolean> | Reads any bcrypt hash, and an argon2 hash. An empty or non-string password or hash is false. A stored value that is not a password hash throws with status 500. A bcrypt hash is retried with the first 72 bytes of a longer password, the way the bcrypt package reads it: for legacy hashes only, a hash written by hash never needs it |
API Summary
| Method | Class | Returns | Description |
|---|---|---|---|
AES.withAlgorithm(algorithm) | AES | AES | Create an AES instance with CBC or GCM mode |
encrypt(opts) | AES | Promise<string> | Encrypt a string message |
decrypt(opts) | AES | Promise<string> | Decrypt a ciphertext string |
encryptFile(opts) | AES | Promise<string> | Encrypt file contents to a string |
decryptFile(opts) | AES | Promise<string> | Decrypt file contents to a string |
RSA.withAlgorithm() | RSA | RSA | Create an RSA instance |
generateDERKeyPair(opts?) | RSA | Promise<{ publicKey: Buffer; privateKey: Buffer }> | Generate a DER-format key pair |
encrypt(opts) | RSA | Promise<string> | Encrypt with a public key |
decrypt(opts) | RSA | Promise<string> | Decrypt with a private key |
ECDH.withAlgorithm(opts?) | ECDH | ECDH | Create an ECDH instance. Passing options requires algorithm alongside hkdfInfo |
generateKeyPair() | ECDH | Promise<{ keyPair: CryptoKeyPair; publicKeyB64: string }> | Generate a P-256 key pair |
importPublicKey(opts) | ECDH | Promise<CryptoKey> | Import a peer's base64 public key |
deriveAESKey(opts) | ECDH | Promise<{ key: CryptoKey; salt: string }> | Derive an AES-256-GCM key via HKDF |
encrypt(opts) | ECDH | Promise<IECDHEncryptedPayload> | Encrypt with a derived AES key |
decrypt(opts) | ECDH | Promise<string> | Decrypt with a derived AES key |
Hash.withAlgorithm(algorithm) | Hash | Hash | Get the memoized instance for an algorithm |
digest(opts) | Hash | string | Plain digest, no secret |
hmac(opts) | Hash | string | Keyed HMAC, secret required |
CredentialHelper.hash(opts) | CredentialHelper | Promise<string> | An argon2id (default) or bcrypt password hash over Bun.password |
CredentialHelper.verify(opts) | CredentialHelper | Promise<boolean> | Check a password against a stored hash |
Troubleshooting
"[validateAlgorithmName] Invalid algorithm name | algorithm: undefined"
Cause: An empty or undefined algorithm was passed to the constructor (or withAlgorithm()).
Fix:
const aes = AES.withAlgorithm('aes-256-gcm'); // not undefined or empty
const rsa = RSA.withAlgorithm(); // no parameter needed
const ecdh = ECDH.withAlgorithm(); // no parameter needed"[ECDH.fromBase64] Invalid base64 input"
Cause: A value passed to an ECDH method - a public key, salt, IV, or ciphertext - is not valid base64. Its length isn't divisible by 4, or it has characters outside A-Za-z0-9+/=.
Fix: Pass base64 strings through exactly as produced by the methods that generated them (publicKeyB64, salt, iv, ct). Do not trim, re-encode, or modify them.
"OperationError: The operation failed for an operation-specific reason"
Cause: Either the ciphertext or auth tag was modified in transit, or encrypt and decrypt used different algorithm modes. The two modes produce incompatible byte layouts.
Fix: Use the same algorithm mode for both encrypt and decrypt.
ECDH decrypt throws even though both sides imported each other's public keys
Cause: Each deriveAESKey call without a salt generates a new random 32-byte salt. If both sides generate their own, they derive different AES keys.
Fix: The initiator calls deriveAESKey without salt and sends the returned salt to the responder. The responder passes that exact salt into their own deriveAESKey call.
"[Hash][hmac] Missing secret for HMAC-..."
Cause: hmac() was called with an empty or missing secret. Unlike the removed hash() function, Hash never silently degrades to a plain digest - it throws instead.
Fix:
const signature = Hash.withAlgorithm(HashAlgorithms.SHA256).hmac({ message: 'text', secret: 'my-hmac-key' });Use digest() instead of hmac() if a plain digest (no secret) is what you actually want.
See also
- Crypto overview - introduction and the most common tasks
- 2026-08-30 changelog -
Hashadded,hash()removed, migration table - Authentication Component - JWT and password verification
- Security Guidelines - cryptographic best practices