# browser Browser-targeted bindings of the cryptography primitives, wired to the Web Crypto API on `globalThis.crypto`. ## Overview This entry point composes the runtime-agnostic core ([`createEncrypt`](https://github.com/AndrewRedican/hyperfrontend/blob/main/libs/cryptography/src/lib/encrypt/create-encrypt.ts), [`createValueCreator`](https://github.com/AndrewRedican/hyperfrontend/blob/main/libs/cryptography/src/lib/create-vault/create-value-creator.ts), hashing, key derivation, key agreement, HKDF expansion, AEAD sealing, time-based passwords) with browser implementations of `subtle`, [`getRandomValues`](https://www.hyperfrontend.dev/docs/libraries/cryptography/browser/#api-getRandomValues), and UTF-8 encoding. The exported function signatures are identical to [`/node`](https://www.hyperfrontend.dev/docs/libraries/cryptography/node.md), so application code that imports from [`@hyperfrontend/cryptography/browser`](https://www.hyperfrontend.dev/docs/libraries/cryptography/browser.md) can be ported between runtimes without changes. ## Usage ```typescript import { encrypt, decrypt, createVault, createHash } from '@hyperfrontend/cryptography/browser' const ciphertext = await encrypt('top-secret', 'user-password') const plaintext = await decrypt(ciphertext, 'user-password') const vault = createVault(true) // singleUse await vault.write('token', 'sk-live-...') const password = vault.getPassword() const token = await vault.read('token', password) // vault closes after read const digest = await createHash('payload') // 64-char hex SHA-256 ``` ## Notes - `subtle` resolves to `globalThis.crypto.subtle` on each use rather than at import, so the entry loads on runtimes without the global (Node.js 18 without `--experimental-global-webcrypto`) and throws a descriptive error when a primitive runs there; a secure context (HTTPS or localhost) is required. - [`getRandomValues`](https://www.hyperfrontend.dev/docs/libraries/cryptography/browser/#api-getRandomValues) is backed by `crypto.getRandomValues` and throws when called with a zero byte length. - Algorithm choices (AES-GCM, PBKDF2 with 100,000 iterations, SHA-256 default) live in the shared core and cannot be overridden per call. ## API Reference ### Functions #### createHash ```typescript function createHash(data: string, algorithm: HashAlgorithm): Promise ``` Creates a cryptographic hash of the provided data using Web Crypto API (browser implementation). **Parameters** | Name | Type | Description | | --- | --- | --- | | `data` | `string` | The string data to hash | | `algorithm` | `HashAlgorithm` | The hash algorithm to use (defaults to SHA-256) (default: `'SHA-256'`) | **Returns** `Promise`: A promise that resolves to the hexadecimal hash string **Example: Creating a hash** ```typescript const hash = await createHash('secret-message') // => '64-character hexadecimal string' ``` #### getRandomValues ```typescript function getRandomValues(byteLength: number): Uint8Array ``` Generates cryptographically secure random values using Web Crypto API (browser implementation). **Parameters** | Name | Type | Description | | --- | --- | --- | | `byteLength` | `number` | The number of random bytes to generate | **Returns** `Uint8Array`: A Uint8Array containing the random bytes **Example: Generating random bytes** ```typescript const randomBytes = getRandomValues(16) // => Uint8Array(16) with cryptographically secure random values ``` #### isSHA256Hash ```typescript function isSHA256Hash(hash: unknown): boolean ``` Validates whether the provided value is a valid SHA-256 hash string. Checks for exactly 64 hexadecimal characters (case-insensitive). **Parameters** | Name | Type | Description | | --- | --- | --- | | `hash` | `unknown` | The value to validate as a SHA-256 hash | **Returns** `boolean`: True if the value is a valid SHA-256 hash string, false otherwise **Example: Validating SHA-256 hashes** ```typescript isSHA256Hash('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855') // => true isSHA256Hash('invalid') // => false ``` ### Interfaces #### EncryptionConfig Configuration for encryption algorithm settings. **Properties** | Name | Type | Description | | --- | --- | --- | | `name` | `"AES-GCM" \| "AES-CBC" \| "AES-CTR"` | Encryption algorithm name (AES-GCM, AES-CBC, or AES-CTR). | #### KeyAgreement One side of an ephemeral elliptic-curve Diffie-Hellman agreement (P-256). The private key never leaves the object: it is a non-extractable `CryptoKey` held in a closure and is garbage-collected with the agreement. Create one agreement per session. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly publicKey` | `Uint8Array` | This side's public key as the 65-byte uncompressed P-256 point, to be sent to the peer | ##### deriveSecret ```typescript deriveSecret(peerPublicKey: Uint8Array): Promise> ``` Derives the 32-byte shared secret from the peer's public key. **Parameters** | Name | Type | Description | | --- | --- | --- | | `peerPublicKey` | `Uint8Array` | The peer's 65-byte uncompressed P-256 point | **Returns** `Promise>`: The shared secret both sides compute #### KeyStretchingConfig Parameters shared by every password-stretching operation in the library. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name` | `"PBKDF2"` | Key derivation algorithm name | | `readonly hash` | `"SHA-256"` | Hash the derivation iterates | | `readonly iterations` | `number` | Iteration count: the work factor an attacker pays per password guess | #### StretchPasswordOptions Options accepted by `stretchPassword`. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly iterations?` | `number` | PBKDF2 iteration count; defaults to the library-wide 100,000 | | `readonly length?` | `number` | Length of the derived material in bits, a positive multiple of 8; defaults to 256 | #### TimeBasedPasswordGenerators Generators for time-based one-time passwords (TOTP). **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly current` | `() => Promise` | Generates the password for the current time window. | | `readonly previous` | `() => Promise` | Generates the password for the previous time window. | | `readonly next` | `() => Promise` | Generates the password for the next time window. | #### Vault Secure vault for storing encrypted key-value pairs. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly write` | `(label: string, value: string) => Promise` | Writes an encrypted value with the given label | | `readonly read` | `(label: string, password: string) => Promise` | Reads and decrypts a value by label, requiring the password | | `readonly getPassword` | `() => string` | Retrieves the current vault password, or null if not set | | `readonly close` | `() => void` | Closes the vault and clears sensitive data from memory | ### Types #### HashAlgorithm Supported cryptographic hash algorithms. ```typescript type HashAlgorithm = "SHA-256" | "SHA-384" | "SHA-512" ``` ### Variables #### createKeyAgreement Creates an ephemeral P-256 key agreement backed by the Web Crypto API. ```typescript const createKeyAgreement: () => Promise ``` **Value** `...` #### createVault ```typescript const createVault: (singleUse?: boolean) => Readonly ``` **Value** `...` #### decrypt ```typescript const decrypt: (encrypted: Uint8Array, password: string) => Promise ``` **Value** `...` #### encrypt ```typescript const encrypt: (message: string, password: string) => Promise> ``` **Value** `...` #### encryptionConfig Frozen encryption configuration to prevent runtime tampering. Using AES-GCM as the default algorithm for authenticated encryption. ```typescript const encryptionConfig: Readonly ``` **Value** `...` #### expandKey Expands input key material into a non-extractable AES-GCM-256 key with HKDF-SHA256 (browser implementation). ```typescript const expandKey: (ikm: Uint8Array, salt: Uint8Array, info: Uint8Array, usages: unknown) => Promise ``` **Value** `...` #### generateKey ```typescript const generateKey: (password: string, salt: Uint8Array) => Promise ``` **Value** `...` #### getTimeBasedPassword Generates a UTC time-based one-time password (TOTP) with configurable time window and offset (browser implementation). Uses Web Crypto API for hash generation. ```typescript const getTimeBasedPassword: (currentUtcTime: Date, baseTimeWindow: number, windowOffset?: -1 | 0 | 1) => Promise ``` **Value** `...` #### getTimeBasedPasswords Generates time-based one-time passwords (TOTP) for current, previous, and next time windows (browser implementation). Useful for handling time synchronization issues by providing passwords across adjacent time windows. ```typescript const getTimeBasedPasswords: (currentUtcTime: Date, baseTimeWindow: number) => Readonly ``` **Value** `...` #### keyStretchingConfig PBKDF2 parameters used by `generateKey` and `stretchPassword`. 100,000 SHA-256 iterations cost roughly 17 ms on commodity hardware, which is the intended price for one password guess and the reason password stretching belongs at session or storage boundaries rather than on a per-message path. ```typescript const keyStretchingConfig: KeyStretchingConfig ``` **Value** `...` #### open Opens a sealed message with AES-GCM under a caller-supplied key and nonce (browser implementation). ```typescript const open: (key: CryptoKey, nonce: Uint8Array, additionalData: Uint8Array, sealed: Uint8Array) => Promise> ``` **Value** `...` #### seal Seals a plaintext with AES-GCM under a caller-supplied key and nonce (browser implementation). ```typescript const seal: (key: CryptoKey, nonce: Uint8Array, additionalData: Uint8Array, plaintext: Uint8Array) => Promise> ``` **Value** `...` #### stretchPassword Stretches a password and a salt into raw key material with PBKDF2-HMAC-SHA256 (browser implementation). ```typescript const stretchPassword: (password: string, salt: Uint8Array, options?: StretchPasswordOptions) => Promise> ``` **Value** `...` #### subtle The Web Crypto `SubtleCrypto` interface, resolved from `globalThis.crypto` on every access, so importing this entry never needs the global to exist and a runtime without it fails at the first primitive call with a descriptive error. ```typescript const subtle: SubtleCrypto ``` **Value** `...` --- Canonical page: https://www.hyperfrontend.dev/docs/libraries/cryptography/browser/ This file: https://www.hyperfrontend.dev/docs/libraries/cryptography/browser.md Documentation index: https://www.hyperfrontend.dev/llms.txt