LogoPear Docs
ReferencesBareModules

bare-crypto

Cryptographic primitives for JavaScript

stable

bare-crypto — Cryptographic primitives for JavaScript. It is a native addon.

Mirrors the Node.js crypto module.

npm i bare-crypto

Usage

const crypto = require('bare-crypto')

const hash = crypto.createHash('sha256')

hash.update('Hello, world!')

const digest = hash.digest('hex')

console.log(digest)

API

Hash

new Hash(algorithm: HashAlgorithm | number, opts?: TransformOptions<CryptoHash>)

Source

Parameters

ParameterTypeDefaultDescription
algorithmHashAlgorithm | numberThe hash algorithm, as a string (e.g. 'sha256', 'sha-256') or a numeric constant from constants.hash.
opts?TransformOptions<CryptoHash>Options forwarded to the Transform constructor from bare-stream.

Throws

  • UNKNOWN_HASHalgorithm is a string that does not name a supported hash algorithm.

Hash.digest(encoding: BufferEncoding): string

Source

Finalize the hash and return the digest. If encoding is provided (and is not 'buffer'), the digest is returned as a string in that encoding; otherwise as a Buffer. Further calls to update() or digest() throw.

Overloads:

digest(encoding: BufferEncoding): string
digest(): Buffer

Parameters

ParameterTypeDefaultDescription
encodingBufferEncodingThe encoding for the returned digest; omit (or pass 'buffer') to get a Buffer.

Hash.HashAlgorithm

type HashAlgorithm = | 'md5'
  | 'sha-1'
  | 'sha-256'
  | 'sha-384'
  | 'sha-512'
  | 'blake2b-256'
  | 'ripemd-160'
Source

Hash.update(data: string, encoding?: BufferEncoding): this

Source

Push data into the hash. If data is a string, it is decoded using encoding (defaults to 'utf8'). Returns the same hash for chaining. Throws once digest() has been called.

Overloads:

update(data: string, encoding?: BufferEncoding): this
update(data: Buffer, encoding?: 'buffer'): this

Parameters

ParameterTypeDefaultDescription
datastringThe data to push into the hash.
encoding?BufferEncodingThe encoding of data when it is a string (defaults to 'utf8').

Hmac

Hmac

new Hmac(algorithm: HashAlgorithm | number, key: string | Buffer, opts?: TransformOptions<CryptoHmac>)
Source

Parameters

ParameterTypeDefaultDescription
algorithmHashAlgorithm | numberThe hash algorithm, as a string (e.g. 'sha256', 'sha-256') or a numeric constant from constants.hash.
keystring | BufferThe HMAC key; a string is decoded using the encoding option (defaults to 'utf8').
opts?TransformOptions<CryptoHmac>Options forwarded to the Transform constructor from bare-stream.

Throws

  • UNKNOWN_HASHalgorithm is a string that does not name a supported hash algorithm.

Hmac.digest(encoding: BufferEncoding): string

Source

Finalize the HMAC. Same semantics as hash.digest().

Overloads:

digest(encoding: BufferEncoding): string
digest(): Buffer

Parameters

ParameterTypeDefaultDescription
encodingBufferEncodingThe encoding for the returned digest; omit (or pass 'buffer') to get a Buffer.

Hmac.update(data: string, encoding?: BufferEncoding): this

Source

Push data into the HMAC. Same semantics as hash.update().

Overloads:

update(data: string, encoding?: BufferEncoding): this
update(data: Buffer, encoding?: 'buffer'): this

Parameters

ParameterTypeDefaultDescription
datastringThe data to push into the HMAC.
encoding?BufferEncodingThe encoding of data when it is a string (defaults to 'utf8').

Cipheriv

Cipheriv

new Cipheriv(algorithm: CipherAlgorithm | number, key: string | Buffer, iv: string | Buffer, opts?: TransformOptions<Cipheriv>)
Source

Parameters

ParameterTypeDefaultDescription
algorithmCipherAlgorithm | numberThe cipher algorithm, as a string or a numeric constant from constants.cipher.
keystring | BufferThe encryption key; must match the algorithm's required length.
ivstring | BufferThe initialization vector / nonce; must match the algorithm's required length.
opts?TransformOptions<Cipheriv>Options forwarded to Transform; may include encoding (defaults to 'utf8') and, for AEAD algorithms, authTagLength (defaults to 16; must be 12, 14, or 16).

Throws

  • UNKNOWN_CIPHERalgorithm is a string that does not name a supported cipher.
  • RangeErrorkey or iv does not match the algorithm's required length, or (AEAD) authTagLength is not 12, 14, or 16.

Cipheriv.final(outputEncoding?: BufferEncoding): string | Buffer

Source

Finalize encryption. For AEAD ciphers, the auth tag becomes available via getAuthTag() after this call.

Parameters

ParameterTypeDefaultDescription
outputEncoding?BufferEncodingIf provided, the final output is returned as a string in this encoding.

getAuthTag(): Buffer

Source

Return the auth tag produced by final(). AEAD ciphers only.

Cipheriv.setAAD(buffer: string | Buffer, opts?: { encoding?: BufferEncoding }): this

Source

Provide additional authenticated data. AEAD ciphers only. The options may include an encoding for string inputs.

Parameters

ParameterTypeDefaultDescription
bufferstring | BufferThe additional authenticated data.
opts?{ encoding?: BufferEncoding }May include an encoding for string buffer inputs.

setAutoPadding(pad: unknown): this

Source

Enable or disable automatic padding. Block ciphers only.

Parameters

ParameterTypeDefaultDescription
padunknowntrue to enable automatic padding, false to disable it.

Cipheriv.update

update(data: string | Buffer, inputEncoding?: BufferEncoding, outputEncoding?: BufferEncoding): string | Buffer
Source

Encrypt a chunk. Returns a Buffer, or a string if outputEncoding is provided. For AEAD ciphers, encrypted output is delivered all at once from final().

Parameters

ParameterTypeDefaultDescription
datastring | BufferThe chunk to encrypt.
inputEncoding?BufferEncodingThe encoding of data when it is a string.
outputEncoding?BufferEncodingIf provided, the encrypted result is returned as a string in this encoding.

Decipheriv

Decipheriv

new Decipheriv(algorithm: CipherAlgorithm | number, key: string | Buffer, iv: string | Buffer, opts?: TransformOptions<Cipheriv>)
Source

Parameters

ParameterTypeDefaultDescription
algorithmCipherAlgorithm | numberThe cipher algorithm, as a string or a numeric constant from constants.cipher.
keystring | BufferThe decryption key; must match the algorithm's required length.
ivstring | BufferThe initialization vector / nonce; must match the algorithm's required length.
opts?TransformOptions<Cipheriv>Accepts the same options as createCipheriv.

Throws

  • UNKNOWN_CIPHERalgorithm is a string that does not name a supported cipher.
  • RangeErrorkey or iv does not match the algorithm's required length, or (AEAD) authTagLength is not 12, 14, or 16.

Decipheriv.final(outputEncoding?: BufferEncoding): string | Buffer

Source

Finalize decryption. For AEAD ciphers, setAuthTag() must be called before final().

Parameters

ParameterTypeDefaultDescription
outputEncoding?BufferEncodingIf provided, the final output is returned as a string in this encoding.

Decipheriv.setAAD(buffer: string | Buffer, opts?: { encoding?: BufferEncoding }): this

Source

Provide additional authenticated data. AEAD ciphers only. The options may include an encoding for string inputs.

Parameters

ParameterTypeDefaultDescription
bufferstring | BufferThe additional authenticated data.
opts?{ encoding?: BufferEncoding }May include an encoding for string buffer inputs.

setAuthTag(authTag: string | Buffer, encoding?: BufferEncoding): this

Source

Set the expected auth tag prior to calling final(). AEAD ciphers only.

Parameters

ParameterTypeDefaultDescription
authTagstring | BufferThe expected authentication tag.
encoding?BufferEncodingThe encoding of authTag when it is a string.

setAutoPadding(pad: boolean): this

Source

Enable or disable automatic padding. Block ciphers only.

Parameters

ParameterTypeDefaultDescription
padbooleantrue to enable automatic padding, false to disable it.

Decipheriv.update

update(data: string | Buffer, inputEncoding?: BufferEncoding, outputEncoding?: BufferEncoding): string | Buffer
Source

Decrypt a chunk. Same semantics as cipher.update().

Parameters

ParameterTypeDefaultDescription
datastring | BufferThe chunk to decrypt.
inputEncoding?BufferEncodingThe encoding of data when it is a string.
outputEncoding?BufferEncodingIf provided, the decrypted result is returned as a string in this encoding.

Functions

createHash(algorithm: HashAlgorithm | number, opts?: TransformOptions<Hash>): Hash

Source

Create a new Hash instance with the specified algorithm. algorithm may be a string (e.g. 'sha256', 'sha-256') or a numeric constant from constants.hash. The options are forwarded to the Transform constructor from bare-stream (<https://github.com/holepunchto/bare-stream>).

Parameters

ParameterTypeDefaultDescription
algorithmHashAlgorithm | numberThe hash algorithm, as a string (e.g. 'sha256', 'sha-256') or a numeric constant from constants.hash.
opts?TransformOptions<Hash>Options forwarded to the Transform constructor from bare-stream.

Throws

  • UNKNOWN_HASHalgorithm is a string that does not name a supported hash algorithm.

createHmac

createHmac(algorithm: HashAlgorithm | number, key: string | Buffer, opts?: TransformOptions<Hmac>): Hmac
Source

Create a new Hmac instance using algorithm and key. key may be a string or ArrayBufferView. If key is a string, an encoding option (defaults to 'utf8') controls how it is decoded. The options are also forwarded to Transform.

Parameters

ParameterTypeDefaultDescription
algorithmHashAlgorithm | numberThe hash algorithm, as a string (e.g. 'sha256', 'sha-256') or a numeric constant from constants.hash.
keystring | BufferThe HMAC key; a string is decoded using the encoding option (defaults to 'utf8').
opts?TransformOptions<Hmac>Options forwarded to the Transform constructor from bare-stream.

Throws

  • UNKNOWN_HASHalgorithm is a string that does not name a supported hash algorithm.

createCipheriv

createCipheriv(algorithm: CipherAlgorithm | number, key: string | Buffer, iv: string | Buffer, opts?: TransformOptions<Cipheriv>): Cipheriv
Source

Create a new Cipheriv instance using algorithm, key, and iv (initialization vector / nonce). key and iv must match the algorithm's required lengths. For AEAD algorithms (e.g. AES128GCM, CHACHA20POLY1305), the options may include an authTagLength (defaults to 16).

Parameters

ParameterTypeDefaultDescription
algorithmCipherAlgorithm | numberThe cipher algorithm, as a string or a numeric constant from constants.cipher.
keystring | BufferThe encryption key; must match the algorithm's required length.
ivstring | BufferThe initialization vector / nonce; must match the algorithm's required length.
opts?TransformOptions<Cipheriv>Options forwarded to Transform; may include encoding (defaults to 'utf8') and, for AEAD algorithms, authTagLength (defaults to 16; must be 12, 14, or 16).

Throws

  • UNKNOWN_CIPHERalgorithm is a string that does not name a supported cipher.
  • RangeErrorkey or iv does not match the algorithm's required length, or (AEAD) authTagLength is not 12, 14, or 16.

createDecipheriv

createDecipheriv(algorithm: CipherAlgorithm | number, key: string | Buffer, iv: string | Buffer, opts?: TransformOptions<Cipheriv>): Decipheriv
Source

Create a new Decipheriv instance using algorithm, key, and iv. Accepts the same options as createCipheriv.

Parameters

ParameterTypeDefaultDescription
algorithmCipherAlgorithm | numberThe cipher algorithm, as a string or a numeric constant from constants.cipher.
keystring | BufferThe decryption key; must match the algorithm's required length.
ivstring | BufferThe initialization vector / nonce; must match the algorithm's required length.
opts?TransformOptions<Cipheriv>Accepts the same options as createCipheriv.

Throws

  • UNKNOWN_CIPHERalgorithm is a string that does not name a supported cipher.
  • RangeErrorkey or iv does not match the algorithm's required length, or (AEAD) authTagLength is not 12, 14, or 16.

randomBytes(size: number): Buffer

Source

Generate size cryptographically secure random bytes.

Overloads:

randomBytes(size: number): Buffer
randomBytes(size: number, callback: (err: Error | null, buffer: Buffer) => void): void

Parameters

ParameterTypeDefaultDescription
sizenumberThe number of random bytes to generate.

randomFill

randomFill<B extends ArrayBuffer | ArrayBufferView>(buffer: B, offset?: number, size?: number): B
Source

Fill buffer with cryptographically secure random bytes, optionally restricted to [offset, offset + size). offset defaults to 0 and size to buffer.byteLength - offset. Returns the same buffer.

Synchronous form: randomFillSync<B extends ArrayBuffer | ArrayBufferView>(buffer: B, offset?: number, size?: number): B

Parameters

ParameterTypeDefaultDescription
bufferBThe buffer to fill.
offset?numberOffset at which filling starts (defaults to 0).
size?numberAmount to fill (defaults to buffer.byteLength - offset).

Throws

  • RangeErroroffset, size, or offset + size is out of range for buffer.

randomUUID(): string

Source

Generate a random RFC 4122 version-4 UUID string.

pbkdf2

pbkdf2(password: string | ArrayBuffer | ArrayBufferView, salt: string | ArrayBuffer | ArrayBufferView, iterations: number, keylen: number, digest: HashAlgorithm | number): Buffer
Source

Derive a key from password and salt using the specified digest algorithm and number of iterations. Returns a keylen-byte Buffer. password and salt may be strings or ArrayBufferViews.

Synchronous form: pbkdf2Sync(password: string | ArrayBufferView, salt: string | ArrayBufferView, iterations: number, keylen: number, digest: HashAlgorithm | number): Buffer

Parameters

ParameterTypeDefaultDescription
passwordstring | ArrayBuffer | ArrayBufferViewThe password to derive the key from.
saltstring | ArrayBuffer | ArrayBufferViewThe salt.
iterationsnumberThe number of PBKDF2 iterations; must be between 1 and 2^32 - 1.
keylennumberThe length in bytes of the derived key.
digestHashAlgorithm | numberThe hash algorithm, as a string or a numeric constant from constants.hash.

Throws

  • RangeErroriterations or keylen is out of range.
  • UNKNOWN_HASHdigest is a string that does not name a supported hash algorithm.

generateKeyPair

generateKeyPair(type: SignatureAlgorithm | Lowercase<SignatureAlgorithm>): {
  publicKey: CryptoKey
  privateKey: CryptoKey
}
Source

Generate a new asymmetric key pair. type may be a string (e.g. 'ed25519') or a numeric constant from constants.keyType.

Parameters

ParameterTypeDefaultDescription
typeSignatureAlgorithm | Lowercase<SignatureAlgorithm>The key type, as a string (e.g. 'ed25519') or a numeric constant from constants.keyType.

Throws

  • UNKNOWN_KEY_TYPEtype is a string that does not name a supported key type.

sign(algorithm: null, data: ArrayBuffer | ArrayBufferView, key: CryptoKey): Buffer

Source

Sign data using key. For Ed25519, algorithm is ignored — pass null. data may be an ArrayBuffer or ArrayBufferView. Returns a Buffer containing the signature.

Parameters

ParameterTypeDefaultDescription
algorithmnullIgnored for Ed25519 — pass null.
dataArrayBuffer | ArrayBufferViewThe data to sign.
keyCryptoKeyThe key to sign with.

verify

verify(algorithm: null, data: ArrayBuffer | ArrayBufferView, key: CryptoKey, signature: Buffer): boolean
Source

Verify that signature is a valid signature over data for key. Returns true or false.

Parameters

ParameterTypeDefaultDescription
algorithmnullIgnored for Ed25519 — pass null.
dataArrayBuffer | ArrayBufferViewThe signed data.
keyCryptoKeyThe key to verify against.
signatureBufferThe signature to check.

timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean

Source

Compare two ArrayBuffers or ArrayBufferViews in constant time. Returns true if a and b contain the same bytes, otherwise false. Throws a RangeError if a and b differ in byte length. Use this whenever comparing MACs, signatures, capability tokens, or other secret-equality checks.

Parameters

ParameterTypeDefaultDescription
aArrayBuffer | ArrayBufferViewThe first buffer to compare.
bArrayBuffer | ArrayBufferViewThe second buffer to compare.

Throws

  • RangeErrora and b differ in byte length.

Constants and variables

constants

constants: {
  hash: Record<HashAlgorithm, number>
  signature: Record<SignatureAlgorithm, number>
  cipher: Record<CipherAlgorithm, number>
  keyType: Record<SignatureAlgorithm, number>
}
Source

The supported algorithm constants: hash (hash algorithms), cipher (symmetric cipher algorithms), signature (signature algorithms), and keyType (asymmetric key types).

webcrypto

Source

A namespace implementing a subset of the W3C Web Crypto API (<https://w3c.github.io/webcrypto>). Exposes Crypto, SubtleCrypto, CryptoKey, getRandomValues, randomUUID, and subtle (a pre-constructed SubtleCrypto instance). Supports HMAC, Ed25519, PBKDF2, and SHA-1 / SHA-256 / SHA-384 / SHA-512.

bare-crypto/web

Functions

getRandomValues<B extends ArrayBuffer | ArrayBufferView>(array: B): B

Source

Fill array with cryptographically secure random bytes and return the same array. Equivalent to randomFillSync(array).

Parameters

ParameterTypeDefaultDescription
arrayBThe buffer to fill with cryptographically secure random bytes.

bare-crypto/global

Constants and variables

crypto

Source

Installed as a global by importing bare-crypto/global, along with Crypto, CryptoKey, and SubtleCrypto.

See also

On this page