npm.io
0.5.2 • Published 7h ago

@better-auth/utils

Licence
MIT
Version
0.5.2
Deps
1
Size
94 kB
Vulns
0
Weekly
0
Stars
234

Better Auth Utils

A simple typescript API for common auth utilities like hashing, encryption, encoding, and OTP generation. Built on top of Web Crypto APIs to provide a unified API for both Node.js (using the Crypto module) and web environments (using the Web Crypto API) through Conditional Exports.

pnpm add @better-auth/utils

Utilities at a Glance

utilities provided by @better-auth/utils:

Utility Description
Hash Hash inputs using sha family hash functions.
HMAC Hash inputs using HMAC with a secret key.
Random String Generate random strings with a specified length and charset.
RSA Perform encryption, decryption, signing, and verification with RSA keys.
ECDSA Perform signing and verification with ECDSA keys.
ML-KEM Establish a shared secret with post-quantum key encapsulation.
ML-DSA Perform post-quantum signing and verification with ML-DSA keys.
OTP Generate and verify one-time passwords.
Base64 Encode and decode data in base64 format.
Hex Encode and decode data in hexadecimal format.
Binary Encode and decode data in binary format.

Hash

Digest provides a way to hash an input using sha family hash functions. It wraps over crypto.digest and provide utilities to encode output in hex or base 64.

import { createHash } from "@better-auth/utils/hash"

const hashBuffer = await createHash("SHA-256").digest("text");
const hashInHex = await createHash("SHA-256", "hex").digest("text");

To encode output in base64

const hashInBase64 = await createHash("SHA-256", "base64").digest("text");

HMAC

The HMAC utility allows you to securely hash data using a secret key and SHA family hash functions. It provides methods to sign, verify, and create a customized HMAC instance with specific hashing algorithms and encoding formats.

Create HMAC

To create an HMAC instance, use the createHMAC function. You can specify the SHA family algorithm ("SHA-256", "SHA-384", or "SHA-512") and the desired encoding format ("none", "hex", "base64", "base64url", or "base64urlnopad").

It takes a secret key and returns a key object which could be used to sign and verify data.

import { createHMAC } from './hmac';

const hmac = createHMAC("SHA-256", "hex"); // Customize algorithm and encoding
Import Key

The importKey method takes a secret key (string, buffer, or typed array) and returns a CryptoKey object that can be used for signing and verifying data.

const secretKey = "my-secret-key"; // Can also be a buffer or TypedArray
const key = await hmac.importKey(secretKey);
Sign

The sign method takes a secret key (or CryptoKey) and data to generate a signature. If you provide a raw secret key, it will automatically be imported.

const key = await hmac.importKey("my-secret-key");
const signature = await hmac.sign(key, "text to sign");
console.log(signature); // Encoded based on the selected encoding format (e.g., hex)

You could also directly sign using the raw string secret key.

const signature2 = await hmac.sign("secret-key",{
    data: "text"
});
Verify

The verify method checks if a given signature matches the data using the secret key. You can provide either a raw secret key or a CryptoKey.

const key = await hmac.importKey("my-secret-key");
const isValid = await hmac.verify(key, "text to sign", signature);
console.log(isValid); // true or false

Random String

Random crypto secure string generator. It wraps over crypto.getRandomValues and provide utilities to generator based on length and charset.

  1. first create a random string generator with desired charset.
import { createRandomStringGenerator } from "@better-auth/utils/random"

export const generateRandomString = createRandomStringGenerator("A-Z", "0-9", "a-z", "-_") 
  1. generate random string based on length.
const randomString = generateRandomString(32)
const randomString2 = generateRandomString(32, "A-Z", "0-9") // override charset

RSA

RSA utilities provide a simple interface to work with RSA cryptographic operations, such as generating key pairs, encrypting and decrypting data, and signing and verifying messages.

Key Pair Generation

You can generate RSA key pairs with specified parameters. The modulusLength can be 2048, 3072, or 4096 bits. By default, the modulusLength is 2048 bits and the hash algorithm is SHA-256.

import { rsa } from "@better-auth/utils/rsa";

const keyPair = await rsa.generateKeyPair(2048, "SHA-256");
const { publicKey, privateKey } = keyPair;

generateKeyPair creates an RSA-OAEP key pair for encryption and decryption. For signing and verification, generate an RSA-PSS key pair with generateSigningKeyPair, which takes the same parameters.

const signingKeyPair = await rsa.generateSigningKeyPair(2048, "SHA-256");
Exporting Keys

Export a public or private key in your preferred format.

const jwk = await rsa.exportKey(publicKey, "jwk");
const spki = await rsa.exportKey(publicKey, "spki");
const signingJwk = await rsa.exportKey(signingKeyPair.publicKey, "jwk");
Importing Keys

Import a key in the jwk format for specific usage (encrypt, decrypt, sign, or verify). encrypt and decrypt import an RSA-OAEP key, while sign and verify import an RSA-PSS key. The optional hash argument must match the JWK alg, such as "SHA-384" for PS384. A JWK without alg or key_ops can be imported for either encryption or signing, so keep separate keys for each.

const encryptionKey = await rsa.importKey(jwk, "encrypt");
const verificationKey = await rsa.importKey(signingJwk, "verify");
Encryption

Encrypt sensitive data using an RSA public key. Input can be a string, ArrayBuffer, or TypedArray. RSA-OAEP encrypts at most 190 bytes with a 2048-bit key and SHA-256, so encrypt larger data with AES-GCM or use ml-kem.

const encryptedData = await rsa.encrypt(publicKey, "Sensitive data");
Decryption

Decrypt encrypted data using the corresponding RSA private key.

const decryptedData = await rsa.decrypt(privateKey, encryptedData);
const originalText = new TextDecoder().decode(decryptedData);
Signing

Sign a message using the private key from generateSigningKeyPair. Input can be a string, ArrayBuffer, or TypedArray. The salt length defaults to 32 bytes. To interoperate with PS384 or PS512, generate or import the key with SHA-384 or SHA-512 and pass 48 or 64 as saltLength.

const signature = await rsa.sign(signingKeyPair.privateKey, "Message to sign");
Verifying

Verify a signature against the original data using the public key from generateSigningKeyPair.

const isValid = await rsa.verify(signingKeyPair.publicKey, {
  signature,
  data: "Message to sign",
});

ECDSA

ECDSA utilities provide a simple interface to perform key pair generation, signing, and verification using elliptic curve cryptography.

Key Pair Generation

You can generate ECDSA key pairs with your preferred curve. Supported curves are "P-256", "P-384", and "P-521".

import { ecdsa } from "@better-auth/utils/ecdsa";

const { privateKey, publicKey } = await ecdsa.generateKeyPair("P-256");
Importing Keys

Import an ECDSA private or public key in the appropriate format. Public keys can also be provided as strings.

const importedPrivateKey = await ecdsa.importPrivateKey(privateKey, "P-256");
const importedPublicKey = await ecdsa.importPublicKey(publicKey, "P-256", true);
Signing

Sign data using the ECDSA private key. The input can be a string or ArrayBuffer. You can specify the hash algorithm, which defaults to "SHA-256".

const signature = await ecdsa.sign(importedPrivateKey, "Message to sign", "SHA-256");
Verifying

Verify a signature against the original data using the ECDSA public key. Input can be a string or ArrayBuffer. Signature verification requires providing the signature, data, and hash algorithm (default: "SHA-256").

const isValid = await ecdsa.verify(importedPublicKey, {
  signature,
  data: "Message to sign",
  hash: "SHA-256",
});
Exporting Keys

Export a public or private key in your preferred format, such as pkcs8 or spki.

const exportedPublicKey = await ecdsa.exportKey(importedPublicKey, "spki");

Post-Quantum

Module Post-quantum alternative
rsa encryption ml-kem
rsa signatures, ecdsa ml-dsa

Symmetric modules such as hash, hmac, otp, and password need no replacement.

ML-KEM

ML-KEM utilities provide post-quantum key encapsulation (FIPS 203). Use them instead of rsa.encrypt to protect data for a recipient's public key. RSA ciphertext recorded today can be decrypted once a large quantum computer exists, while ML-KEM is designed to stay secure against quantum computers.

The sender encapsulates a random shared key with the recipient's public key and sends the ciphertext. The recipient decapsulates the ciphertext with the private key to get the same shared key. The shared key is 32 bytes. Derive the encryption key from it with HKDF, as in Encrypting Data.

ML-KEM needs runtime support for the post-quantum Web Crypto algorithms: Node.js 24.7 or later, Bun 1.4 or later, Deno 2.9 or later, or Cloudflare Workers with the webcrypto_modern_algorithms compatibility flag. Other runtimes, including browsers without these algorithms, throw an error at the call. Node.js 24 prints an ExperimentalWarning the first time each algorithm is used.

Key Pair Generation

Generate a key pair with "ML-KEM-768" (default) or "ML-KEM-1024". The private key is returned in pkcs8 format and the public key in spki format.

import { mlKem } from "@better-auth/utils/ml-kem";

const { privateKey, publicKey } = await mlKem.generateKeyPair("ML-KEM-768");
Importing Keys

Import a pkcs8 private key or an spki public key with the parameter set it was generated with. Private keys must be in the seed-only PKCS#8 form that generateKeyPair returns.

const recipientPrivateKey = await mlKem.importPrivateKey(privateKey, "ML-KEM-768");
const recipientPublicKey = await mlKem.importPublicKey(publicKey, "ML-KEM-768");
Encapsulation

Encapsulate a new shared key with the recipient's public key. Send the ciphertext to the recipient and keep the sharedKey secret.

const { sharedKey, ciphertext } = await mlKem.encapsulate(recipientPublicKey);
Decapsulation

Decapsulate the ciphertext with the recipient's private key to get the same shared key.

const recipientSharedKey = await mlKem.decapsulate(recipientPrivateKey, ciphertext);

A modified ciphertext of the right length does not throw. It yields a different shared key, so decryption fails. ML-KEM does not authenticate the sender, so sign the message with ML-DSA when that matters.

Encrypting Data

Derive an AES-GCM key from the shared key with HKDF, binding the ciphertext and the recipient public key in the salt. Send the ciphertext, iv, and encrypted data together.

const salt = await new Blob([ciphertext, publicKey]).arrayBuffer();
const hkdfKey = await crypto.subtle.importKey("raw", sharedKey, "HKDF", false, ["deriveKey"]);
const aesKey = await crypto.subtle.deriveKey(
  {
    name: "HKDF",
    hash: "SHA-256",
    salt,
    info: new TextEncoder().encode("my-app encryption v1"),
  },
  hkdfKey,
  {
    name: "AES-GCM",
    length: 256,
  },
  false,
  ["encrypt"],
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
  {
    name: "AES-GCM",
    iv,
  },
  aesKey,
  new TextEncoder().encode("Sensitive data"),
);

The recipient derives the same key from recipientSharedKey with the "decrypt" usage and calls crypto.subtle.decrypt with the same iv.

Exporting Keys

Export a key in pkcs8, spki, or jwk format. The key must be imported with extractable set to true. jwk export depends on the runtime.

const extractableKey = await mlKem.importPublicKey(publicKey, "ML-KEM-768", true);
const exportedPublicKey = await mlKem.exportKey(extractableKey, "spki");

ML-DSA

ML-DSA utilities provide key pair generation, signing, and verification with ML-DSA (FIPS 204), a post-quantum signature algorithm. The API has the same shape as ECDSA. Signatures use pure ML-DSA, with an empty context unless you pass one.

ML-DSA runs on Node.js 24.7 or later, Bun 1.4 or later, Deno 2.9 or later, and Cloudflare Workers with the webcrypto_modern_algorithms compatibility flag. Other runtimes, including browsers without these algorithms, reject at the call. Node.js 24 prints an ExperimentalWarning the first time each algorithm is used.

Key Pair Generation

Generate an ML-DSA key pair with a parameter set. Supported parameter sets are "ML-DSA-44", "ML-DSA-65", and "ML-DSA-87". The parameter set is required.

import { mlDsa } from "@better-auth/utils/ml-dsa";

const { privateKey, publicKey } = await mlDsa.generateKeyPair("ML-DSA-65");

Signatures are 2420, 3309, and 4627 bytes for ML-DSA-44, ML-DSA-65, and ML-DSA-87, much larger than ECDSA signatures.

Importing Keys

Import an ML-DSA private key in pkcs8 format or a public key in spki format. Pass true as the third argument to make the key exportable. Importing a key with a different parameter set than the one it was encoded for rejects with a DataError. Private keys must be in the seed-only PKCS#8 form that generateKeyPair returns.

const signingKey = await mlDsa.importPrivateKey(privateKey, "ML-DSA-65");
const verifyingKey = await mlDsa.importPublicKey(publicKey, "ML-DSA-65", true);
Signing

Sign data using the ML-DSA private key. The input can be a string, ArrayBuffer, or typed array. Signatures are randomized, so signing the same data twice gives different signatures. Pass { context } with up to 255 bytes to bind a signature to one purpose. Leave it out for JOSE and COSE.

const signature = await mlDsa.sign(signingKey, "Message to sign");
Verifying

Verify a signature against the original data using the ML-DSA public key. Pass the same context that was used for signing, if any. Keys of other algorithms are rejected with a TypeError.

const isValid = await mlDsa.verify(verifyingKey, {
  signature,
  data: "Message to sign",
});
Exporting Keys

Export an exportable key in pkcs8, spki, or jwk format.

const exportedPublicKey = await mlDsa.exportKey(verifyingKey, "spki");
const publicJwk = await mlDsa.exportKey(verifyingKey, "jwk");

OTP

The OTP utility provides a simple and secure way to generate and verify one-time passwords (OTPs), commonly used in multi-factor authentication (MFA) systems. It includes support for both HOTP (HMAC-based One-Time Password) and TOTP (Time-based One-Time Password) standards.

It's implemented based on RFC 4226 and RFC 6238.

Generating HOTP

HOTP generates a one-time password based on a counter value and a secret key. The counter should be incremented for each new OTP.

import { createOTP } from "@better-auth/utils/otp";
const secret = "my-super-secret-key";
const counter = 1234;
const otp = await createOTP(secret, {
  digits: 6,
}).hotp(counter);
Generating TOTP

TOTP generates a one-time password based on the current time and a secret key. The time step is typically 30 seconds.

import { createOTP } from "@better-auth/utils/otp";
const secret = "my-super-secret-key"
const otp = await createOTP(secret, {
  digits: 6,
  period: 30,
}).totp();
Verifying TOTP

Verify a TOTP against the secret key and a specified time window. By default, codes from one period before and after the current one are also accepted.

import { createOTP } from "@better-auth/utils/otp";
const secret = "my-super-secret-key"
const isValid = await createOTP(secret, {
  digits: 6,
  period: 30,
}).verify(otp);

You can also specify the time window as the number of periods to accept on each side.

import { createOTP } from "@better-auth/utils/otp";
const isValid = await createOTP(secret).verify(otp, { window: 2 });
Generate URL for Authenticator App

Generate a URL for provisioning a TOTP secret key in an authenticator app.

  • issuer - The name of the service or app.
  • account - The user's email or username.
import { createOTP } from "@better-auth/utils/otp";

const secret = "my-super-secret-key";
const qrCodeUrl = createOTP(secret).url("my-app", "user@email.com"); 

The URL includes the algorithm parameter only when hash is not SHA-1, so default URLs carry no algorithm.

Using a Byte Secret

createOTP also accepts a Uint8Array or ArrayBuffer as the HMAC key. Strings are used as UTF-8 bytes, so decode encoded secrets first, such as the Base32 secret in an otpauth:// URI.

import { base32 } from "@better-auth/utils/base32";
import { createOTP } from "@better-auth/utils/otp";

const secret = base32.decode("JBSWY3DPEHPK3PXP");
const isValid = await createOTP(secret).verify(otp);
Choosing the Hash

createOTP uses HMAC-SHA-1 by default, as RFC 4226 defines. RFC 6238 also allows HMAC-SHA-256 and HMAC-SHA-512 for TOTP. Pass hash to use one of them for hotp, totp, verify and url.

import { createOTP } from "@better-auth/utils/otp";

const otp = createOTP(secret, {
  hash: "SHA-256",
});
const code = await otp.totp();
const uri = otp.url("my-app", "user@email.com"); // ...&algorithm=SHA256

Not every authenticator app honors the algorithm parameter. Some ignore it and show SHA-1 codes that will never verify, so keep the default unless you control which apps your users scan with. Use a secret at least as long as the hash output: 20 bytes for SHA-1, 32 for SHA-256 and 64 for SHA-512.

Base64

Base64 utilities provide a simple interface to encode and decode data in base64 format.

Encoding

Encode data in base64 format. Input can be a string, ArrayBuffer, or number-based TypedArray. BigInt typed arrays are not supported.

import { base64 } from "@better-auth/utils/base64";

const encodedData = base64.encode("Data to encode");

options:

  • padding - Include padding characters (=) at the end of the encoded string
const encodedData = base64.encode("Data to encode", { url: true, padding: false });
Decoding

Decode base64-encoded data. Input can be a string or ArrayBuffer.

const decodedData = await base64.decode(encodedData);

It automatically detects if the input is URL-safe and includes padding characters.

Base64Url

Url safe alternative

import { base64Url } from "@better-auth/utils/base64";

const encodedData = base64Url.encode("Data to encode");

Hex

Hex utilities provide a simple interface to encode and decode data in hexadecimal format.

Encoding

Encode data in hexadecimal format. Input can be a string, ArrayBuffer, or number-based TypedArray. BigInt typed arrays are not supported.

import { hex } from "@better-auth/utils/hex";

const encodedData = hex.encode("Data to encode");
Decoding

Decode hexadecimal-encoded data into a string. Input can be a string, ArrayBuffer, or TypedArray. Uppercase and lowercase hexadecimal are both accepted.

const decodedData = hex.decode(encodedData);
Converting to bytes

Convert a hexadecimal string into its raw bytes. Use this when the decoded value is binary data, such as a signature or key, rather than UTF-8 text.

const bytes = hex.toBytes("48656c6c6f"); // Uint8Array([72, 101, 108, 108, 111])

Binary

A utilities provide a simple interface to encode and decode data in binary format. It uses TextEncode and TextDecoder to encode and decode data respectively.

Encoding
import { binary } from "@better-auth/util/binary"

const data = binary.encode("Hello World!")
Decoding
import { binary } from "@better-auth/util/binary"

const data = binary.decode(new Unit8Array([[72, 101, 108, 108, 111]]))

License

MIT

Keywords