Initializing Secure Environment...

@bturkis/keygen

Cryptographically secure key generators for Node.js, Deno, and browsers. Uses Web Crypto API with rejection sampling — zero bias.

TypeScriptESM + CJS<8KB gzippedZero-bias

Installation

npmnpm install @bturkis/keygen
pnpmpnpm add @bturkis/keygen
yarnyarn add @bturkis/keygen

Quick Example

import { generatePassword, generateHexKey } from "@bturkis/keygen";

const [password] = generatePassword({ length: 16 });
const [apiKey] = generateHexKey({ bytes: 32, prefix: "sk_" });

Generators

#

generatePassword

(options?: PasswordOptions) => string[]

Generate secure passwords with customizable character sets. Guarantees at least one character from each enabled class (uppercase, lowercase, digits, symbols) using Fisher-Yates shuffle for unbiased placement. Quotes are excluded from default symbols for shell/SQL safety.

Parameters

ParameterTypeDefaultDescription
lengthnumber16Length of each password
countnumber1Number of passwords to generate
uppercasebooleantrueInclude uppercase letters A-Z
lowercasebooleantrueInclude lowercase letters a-z
numbersbooleantrueInclude digits 0-9
symbolsbooleantrueInclude special characters
customSymbolsstringCustom special characters (overrides default set)
minEntropynumberMinimum entropy bits required (throws if config too weak)

Returns

string[] — Array of generated passwords

Example

import { generatePassword } from "@bturkis/keygen";

// Default: 16 chars, all character classes
const [password] = generatePassword();

// No symbols, shorter
const simple = generatePassword({ length: 12, symbols: false });

// Custom special characters
const custom = generatePassword({ customSymbols: "!@#$" });

// Bulk generation with entropy enforcement
const bulk = generatePassword({
  length: 20,
  count: 100,
  minEntropy: 128,
});

💡 Throws an error if the configured length and character sets produce fewer entropy bits than minEntropy.

#

generateHexKey

(options?: HexKeyOptions) => string[]

Generate cryptographically secure hex keys. Perfect for API keys, JWT secrets, AES encryption keys, and any application requiring hex-encoded random bytes.

Parameters

ParameterTypeDefaultDescription
bytesnumber32Number of random bytes (32 = 256-bit key)
countnumber1Number of keys to generate
prefixstring""String to prepend to each key
suffixstring""String to append to each key
separatorstring""Character between hex segments
separatorIntervalnumber0Hex characters between separators
uppercasebooleanfalseOutput uppercase hex (A-F vs a-f)

Returns

string[] — Array of hex key strings

Example

import { generateHexKey } from "@bturkis/keygen";

// 256-bit key (32 bytes)
const [key] = generateHexKey();
// => "a1b2c3d4e5f6..."

// API key with prefix
const [apiKey] = generateHexKey({
  bytes: 32,
  prefix: "sk_live_",
});
// => "sk_live_a1b2c3d4..."

// Formatted with separators (like MAC address)
const [formatted] = generateHexKey({
  bytes: 6,
  separator: ":",
  separatorInterval: 2,
  uppercase: true,
});
// => "A1:B2:C3:D4:E5:F6"
#

generateUUID

(options?: UUIDOptions) => string[]

Generate RFC 4122 compliant UUID v4 identifiers with 122 bits of randomness. Suitable for database primary keys, session identifiers, and distributed system IDs.

Parameters

ParameterTypeDefaultDescription
countnumber1Number of UUIDs to generate

Returns

string[] — Array of UUID v4 strings

Example

import { generateUUID } from "@bturkis/keygen";

// Single UUID
const [id] = generateUUID();
// => "550e8400-e29b-41d4-a716-446655440000"

// Batch generation
const ids = generateUUID({ count: 10 });
// => ["...", "...", ...]
#

generateSecretKey

(options?: SecretKeyOptions) => string[]

Generate high-entropy secret keys with mixed characters including letters, digits, and special characters. Ideal for environment variables, JWT signing secrets, and encryption keys.

Parameters

ParameterTypeDefaultDescription
lengthnumber32Length of each key
countnumber1Number of keys to generate

Returns

string[] — Array of secret key strings

Example

import { generateSecretKey } from "@bturkis/keygen";

// 32-character secret
const [secret] = generateSecretKey();
// => "x!K9@mP2#qR5&wT8yL3$vN6..."

// Long key for .env files
const envSecrets = generateSecretKey({
  length: 64,
  count: 3,
});
#

generateRandomString

(options?: RandomStringOptions) => string[]

Generate alphanumeric random strings (A-Z, a-z, 0-9). No special characters — safe for URLs, filenames, database identifiers, and any context where special characters could cause issues.

Parameters

ParameterTypeDefaultDescription
lengthnumber16Length of each string
countnumber1Number of strings to generate

Returns

string[] — Array of alphanumeric strings

Example

import { generateRandomString } from "@bturkis/keygen";

// URL-safe token
const [token] = generateRandomString();
// => "Abc123Xyz456DefG"

// Longer tokens in bulk
const tokens = generateRandomString({
  length: 24,
  count: 5,
});

Utilities

#

textToKey

(text: string, options?: TextToKeyOptions) => Promise<string>

Convert text to a deterministic hash key using SHA algorithms. Same input always produces the same output. Uses the Web Crypto API's SubtleCrypto.digest() method.

Parameters

ParameterTypeDefaultDescription
textstring(required) Input text to hash
algorithm"SHA-1" | "SHA-256" | "SHA-384" | "SHA-512""SHA-256"Hash algorithm to use

Returns

Promise<string> — Hex-encoded hash string

Example

import { textToKey } from "@bturkis/keygen";

// SHA-256 (default)
const hash = await textToKey("hello world");
// => "b94d27b9934d3e08..."

// SHA-512 for maximum security
const hash512 = await textToKey("hello", {
  algorithm: "SHA-512",
});

// SHA-1 (fast, non-cryptographic use only)
const hash1 = await textToKey("data", {
  algorithm: "SHA-1",
});

💡 Async function. SHA-1 is deprecated for cryptographic use — prefer SHA-256 or higher.

#

calculateEntropy

(params: { bytes?, charPool?, length? }) => EntropyInfo

Calculate entropy information for a key configuration. Supports two modes: by raw bytes (for hex keys) or by character pool size and length (for passwords/strings).

Parameters

ParameterTypeDefaultDescription
bytesnumberNumber of random bytes (entropy = bytes × 8)
charPoolnumberSize of the character pool
lengthnumberLength of the generated string

Returns

EntropyInfo — { bits, strength: "weak" | "fair" | "strong" | "very-strong", label }

Example

import { calculateEntropy } from "@bturkis/keygen";

// Hex key entropy (32 bytes = 256 bits)
const hexInfo = calculateEntropy({ bytes: 32 });
// => { bits: 256, strength: "very-strong",
//      label: "Very Strong - Maximum security" }

// Password entropy (92 chars × 16 length)
const pwdInfo = calculateEntropy({
  charPool: 92,
  length: 16,
});
// => { bits: 104, strength: "fair", ... }

💡 Strength thresholds: weak (<64 bits), fair (64-127), strong (128-255), very-strong (≥256).

#

checkPasswordStrength

(password: string) => PasswordStrength

Analyze password strength beyond simple entropy. Detects sequential characters (abc, 123), repeated characters (aaa), common patterns (password, qwerty), and evaluates character class diversity.

Parameters

ParameterTypeDefaultDescription
passwordstring(required) The password to analyze

Returns

PasswordStrength — { score: 0-100, issues: string[], rating: "weak" | "fair" | "strong" | "very-strong" }

Example

import { checkPasswordStrength } from "@bturkis/keygen";

// Weak password
const weak = checkPasswordStrength("abc123!!");
// => { score: 45, rating: "fair",
//      issues: ["Sequential characters detected",
//               "Repeated characters detected"] }

// Strong password
const strong = checkPasswordStrength("xK9@mP2#qR5&wT8!");
// => { score: 95, rating: "very-strong",
//      issues: [] }

💡 Checks: length (min 8/12), character class diversity, sequential chars, repeated chars, and 10 common patterns.