bcryptjs Documentation

repository·main·Indexed 26 days ago

https://github.com/dcodeio/bcrypt.js

An optimized, zero-dependency implementation of bcrypt in pure JavaScript with TypeScript support. Compatible with the Node.js C++ bcrypt binding, it works in both Node.js and browser environments. It provides synchronous and asynchronous APIs for hashing and comparing passwords, as well as a CLI tool for terminal-based hashing.

Tokens
2.2K
Snippets
3
Records
19
Agent score
87%

What's inside bcryptjs

  1. Use bcryptjs via CDN

    main

    You can use bcryptjs directly in the browser via several CDNs. Note that when using the ESM variant in a browser, you must stub out the crypto import (e.g., using an import map). Bundlers typically handle this automatically.

    jsDelivr

    • ESM: https://cdn.jsdelivr.net/gh/dcodeIO/bcrypt.js@TAG/index.js
    • ESM: https://cdn.jsdelivr.net/npm/bcryptjs@VERSION/index.js
    • UMD: https://cdn.jsdelivr.net/npm/bcryptjs@VERSION/umd/index.js

    unpkg

    • ESM: https://unpkg.com/bcryptjs@VERSION/index.js
    • UMD: https://unpkg.com/bcryptjs@VERSION/umd/index.js

    Replace TAG or VERSION with a specific version or omit it to use the latest.

  2. Hash and compare passwords asynchronously

    main

    Use the asynchronous API (Promises or Callbacks) to avoid blocking the event loop. Asynchronous APIs split operations into small chunks to yield execution to the JS event queue.

    // Using Promises (async/await)
    const salt = await bcrypt.genSalt(10);
    const hash = await bcrypt.hash("B4c0/\/", salt);
    await bcrypt.compare("B4c0/\/", hash); // true
    
    // Auto-gen salt and hash with Promise
    const hash = await bcrypt.hash("B4c0/\/", 10);
    
    // Using Callbacks
    bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash("B4c0/\/", salt, function (err, hash) {
        // Store hash
      });
    });
    
    bcrypt.compare("B4c0/\/", hash, (err, res) => {
      // res === true
    });
  3. Check if a password will be truncated

    main
    Bcrypt has a maximum input length of 72 bytes. Because UTF-8 characters can use up to 4 bytes, you should use bcrypt.truncates(password) to check if a password will be truncated before hashing it.
  4. Reference: bcryptjs Callback and Callback Types

    main

    When using callback-based APIs, the following types are used:

    • Callback<T>: (err: Error | null, result?: T) => void - Called with an error on failure or a value of type T on success.
    • ProgressCallback: (percentage: number) => void - Called with the percentage of rounds completed (0.0 - 1.0), maximally once per 100ms.
    • RandomFallback: (length: number) => number[] - Used to obtain random bytes when Web Crypto and Node.js crypto are unavailable.
  5. Reference: bcryptjs Functions

    main

    The following functions are exported by bcryptjs:

    • genSaltSync(rounds?: number): string - Synchronously generates a salt. Rounds default to 10.
    • genSalt(rounds?: number): Promise<string> - Asynchronously generates a salt (Promise).
    • genSalt(rounds: number, callback: Callback<string>): void - Asynchronously generates a salt (Callback).
    • truncates(password: string): boolean - Tests if a password length > 72 bytes (UTF-8).
    • hashSync(password: string, salt?: number | string): string - Synchronously generates a hash.
    • hash(password: string, salt: number | string): Promise<string> - Asynchronously generates a hash (Promise).
    • hash(password: string, salt: number | string, callback: Callback<string>, progressCallback?: ProgressCallback): void - Asynchronously generates a hash (Callback).
    • compareSync(password: string, hash: string): boolean - Synchronously tests a password against a hash.
    • compare(password: string, hash: string): Promise<boolean> - Asynchronously compares a password against a hash (Promise).
    • compare(password: string, hash: string, callback: Callback<boolean>, progressCallback?: ProgressCallback): void - Asynchronously compares a password against a hash (Callback).
    • getRounds(hash: string): number - Gets the number of rounds used in the hash.
    • getSalt(hash: string): string - Gets the salt portion from a hash (does not validate hash).
    • setRandomFallback(random: RandomFallback): void - Sets a custom PRNG fallback if Web Crypto or Node.js crypto are unavailable.
  6. Troubleshoot bcrypt.js validation errors

    main

    When using hash or hashSync, the library performs several validations. If these fail, the library will either throw an error (in synchronous mode) or pass an error to the callback (in asynchronous mode).

    Common error scenarios include:

    • Illegal number of rounds: The rounds value must be between 4 and 31.
    • Illegal salt length: The provided salt does not match the expected BCRYPT_SALT_LEN.
    • Invalid string / salt: The password or salt provided is not a string.
    • Invalid salt version: The salt does not start with the expected version prefix (e.g., $2).
    • Invalid salt revision: The salt revision (e.g., a, b, or y) is unrecognized or incorrectly formatted.
    • Missing salt rounds: The salt string is missing the required rounds information.
  7. Extract information from a bcrypt hash

    main

    Use these utility functions to inspect an existing bcrypt hash string.

    • getRounds(hash): Returns the number of rounds used to encrypt the hash.
    • getSalt(hash): Returns the salt portion of the hash (does not validate the hash).
    • truncates(password): Returns true if the password's UTF-8 byte length is greater than 72 bytes, meaning it will be truncated when hashed.
  8. Set a custom random fallback for environments without Web Crypto or Node.js crypto

    main

    If your environment lacks both the Web Crypto API and the Node.js crypto module, you must provide a custom pseudo-random number generator (PRNG) using setRandomFallback.

    Warning: The function you provide must be cryptographically secure and properly seeded to ensure the security of the generated hashes.

  9. Use encodeBase64 and decodeBase64

    main

    The library exports utility functions to encode and decode byte arrays using the custom bcrypt base64 alphabet.

    • encodeBase64(bytes, length): Encodes a byte array to a base64 string using the custom bcrypt alphabet, up to the specified length.
    • decodeBase64(string, length): Decodes a base64 encoded string using the custom bcrypt alphabet, up to the specified length, returning an array of numbers.