### Synchronously Hash Passwords with bcryptjs Source: https://context7.com/dcodeio/bcrypt.js/llms.txt Generates bcrypt password hashes synchronously using bcrypt.hashSync, accepting either a pre-generated salt or a round count. Demonstrates multiple usage patterns and includes a user registration example. Returns a 60-character hash suitable for storage. ```JavaScript import bcrypt from "bcryptjs"; // Method 1: Using pre-generated salt const salt = bcrypt.genSaltSync(10); const hash1 = bcrypt.hashSync("myPassword", salt); console.log(hash1); // "$2b$10$N9qo8uLOickgx2ZMRZoMye..." // Method 2: Auto-generate salt with specified rounds const hash2 = bcrypt.hashSync("myPassword", 10); // Method 3: Auto-generate salt with default rounds (10) const hash3 = bcrypt.hashSync("myPassword"); // All three methods produce valid 60-character hashes console.log(hash1.length); // 60 console.log(hash2.length); // 60 console.log(hash3.length); // 60 // Real-world user registration example function registerUser(username, password) { const hash = bcrypt.hashSync(password, 10); // Store hash in database return { username, passwordHash: hash }; } const user = registerUser("john_doe", "SecurePass123!"); console.log(user); // { username: "john_doe", passwordHash: "$2b$10$..." } ``` -------------------------------- ### Import bcrypt.js library in TypeScript Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md This snippet demonstrates importing the bcryptjs library in a TypeScript file using ES module syntax. It requires installing the library via npm. No additional dependencies are needed for the import itself. ```typescript import bcrypt from "bcryptjs"; ``` -------------------------------- ### Configure Custom PRNG with setRandomFallback (JavaScript) Source: https://context7.com/dcodeio/bcrypt.js/llms.txt Sets a custom pseudo-random number generator (PRNG) for bcrypt.js in environments lacking Web Crypto API or Node.js crypto. The provided PRNG must be cryptographically secure and properly seeded. Examples show using Math.random() (not secure), Web Crypto API, and a hypothetical secure random library. ```javascript import bcrypt from "bcryptjs"; // Example: Using a hypothetical secure random library function setupCustomRandom() { // WARNING: Math.random() is NOT cryptographically secure! // This is for demonstration only - use a proper CSPRNG bcrypt.setRandomFallback((length) => { const bytes = []; for (let i = 0; i < length; i++) { // In production, use a cryptographically secure source bytes.push(Math.floor(Math.random() * 256)); } return bytes; }); } // Better example: Using Web Crypto API fallback if (typeof crypto !== "undefined" && crypto.getRandomValues) { bcrypt.setRandomFallback((length) => { const bytes = new Uint8Array(length); crypto.getRandomValues(bytes); return Array.from(bytes); }); } // Example with hypothetical secure library import secureRandom from "some-secure-random-library"; bcrypt.setRandomFallback((length) => { return secureRandom.getBytes(length); }); // After setting fallback, use bcrypt normally const salt = bcrypt.genSaltSync(10); const hash = bcrypt.hashSync("password", salt); // Note: Only necessary in environments lacking native crypto // Browser and Node.js environments have built-in support ``` -------------------------------- ### Asynchronous Password Comparison with bcrypt.js Source: https://context7.com/dcodeio/bcrypt.js/llms.txt Illustrates asynchronous password comparison using bcrypt.js's `compare` method. This non-blocking approach is ideal for web servers and other I/O-bound operations. It supports both Promises and callbacks, and includes an optional progress callback for monitoring intensive comparisons. Requires the 'bcryptjs' package. ```javascript import bcrypt from "bcryptjs"; // Promise-based comparison async function authenticateUser(inputPassword, storedHash) { try { const isMatch = await bcrypt.compare(inputPassword, storedHash); return isMatch; } catch (error) { console.error("Authentication error:", error); return false; } } // Callback-based comparison function login(password, hash, callback) { bcrypt.compare(password, hash, (err, isMatch) => { if (err) { callback(err, null); return; } callback(null, isMatch); }); } // With progress callback for high-round hashes bcrypt.compare("password", hash, (err, isMatch) => { if (err) throw err; console.log("Match result:", isMatch); }, (progress) => { console.log(`Comparison progress: ${(progress * 100).toFixed(1)}%`); } ); // Express.js login endpoint app.post("/api/login", async (req, res) => { const { email, password } = req.body; try { const user = await db.users.findOne({ email }); if (!user) { return res.status(401).json({ error: "Invalid credentials" }); } const isValid = await bcrypt.compare(password, user.passwordHash); if (isValid) { // Generate session token... res.json({ success: true, token: "..." }); } else { res.status(401).json({ error: "Invalid credentials" }); } } catch (error) { res.status(500).json({ error: "Login failed" }); } }); ``` -------------------------------- ### Asynchronous Password Hashing with bcrypt.js Source: https://context7.com/dcodeio/bcrypt.js/llms.txt Demonstrates how to asynchronously generate password hashes using bcrypt.js. Supports Promise-based and callback patterns, with an option for progress monitoring during long operations. Requires the 'bcryptjs' package. ```javascript import bcrypt from "bcryptjs"; // Promise-based usage with auto-generated salt async function hashPassword(password) { try { const hash = await bcrypt.hash(password, 10); console.log("Hash generated:", hash); return hash; } catch (error) { console.error("Hashing failed:", error); throw error; } } // Using pre-generated salt async function hashWithSalt(password) { const salt = await bcrypt.genSalt(12); const hash = await bcrypt.hash(password, salt); return hash; } // Callback-based with progress monitoring bcrypt.hash("myPassword", 12, (err, hash) => { if (err) throw err; console.log("Final hash:", hash); }, (progress) => { console.log(`Hashing progress: ${Math.round(progress * 100)}%`); } ); // Express.js registration endpoint example app.post("/api/register", async (req, res) => { const { email, password } = req.body; try { const hash = await bcrypt.hash(password, 10); await db.users.insert({ email, passwordHash: hash }); res.status(201).json({ message: "User created" }); } catch (error) { res.status(500).json({ error: "Registration failed" }); } }); ``` -------------------------------- ### Utility Functions Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md Utility functions for retrieving salt rounds and setting random fallback. ```APIDOC ## bcrypt.getRounds ### Description Gets the number of rounds used to encrypt the specified hash. ### Method `bcrypt.getRounds(hash: string): number` ### Parameters - **hash** (string) - Required - The hash string. ### Response - **number** - The number of rounds used. ### Request Example ```javascript const rounds = bcrypt.getRounds('$2b$10$N9qo8uLOickgx2ZMRZoMye7j.5s.jA9o.jJ8a2J6Lq7o0o3jJj5j'); console.log(rounds); ``` ### Response Example ```json 10 ``` ## bcrypt.getSalt ### Description Gets the salt portion from a hash. Does not validate the hash. ### Method `bcrypt.getSalt(hash: string): string` ### Parameters - **hash** (string) - Required - The hash string. ### Response - **string** - The salt portion of the hash. ### Request Example ```javascript const salt = bcrypt.getSalt('$2b$10$N9qo8uLOickgx2ZMRZoMye7j.5s.jA9o.jJ8a2J6Lq7o0o3jJj5j'); console.log(salt); ``` ### Response Example ```json "$2b$10$N9qo8uLOickgx2ZMRZoMye" ``` ## bcrypt.setRandomFallback ### Description Sets the pseudo random number generator to use as a fallback if neither Web Crypto API nor Node.js crypto are available. It is highly important that the PRNG used is cryptographically secure and that it is seeded properly! ### Method `bcrypt.setRandomFallback(random: RandomFallback): void` ### Parameters - **random** (RandomFallback) - Required - A function that returns an array of random bytes. ### Request Example ```javascript bcrypt.setRandomFallback((length) => { // Implement a cryptographically secure random number generator const randomBytes = new Uint8Array(length); // Fill randomBytes with secure random data return Array.from(randomBytes); }); ``` ### Response Example (No direct response, but the fallback is set) ``` -------------------------------- ### Salt Generation Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md Functions for generating salt, both synchronously and asynchronously. ```APIDOC ## bcrypt.genSaltSync ### Description Synchronously generates a salt. ### Method `bcrypt.genSaltSync(rounds?: number): string` ### Parameters - **rounds** (number) - Optional - Number of rounds to use for salt generation. Defaults to 10. ### Response - **string** - The generated salt. ### Request Example ```javascript const salt = bcrypt.genSaltSync(12); ``` ### Response Example ```json "$2b$10$N9qo8uLOickgx2ZMRZoMye7j.5s.jA9o.jJ8a2J6Lq7o0o3jJj5j" ``` ## bcrypt.genSalt (async with Promise) ### Description Asynchronously generates a salt using Promises. ### Method `bcrypt.genSalt(rounds?: number): Promise` ### Parameters - **rounds** (number) - Optional - Number of rounds to use for salt generation. Defaults to 10. ### Response - **Promise** - A promise that resolves with the generated salt. ### Request Example ```javascript bcrypt.genSalt(10).then(salt => { console.log(salt); }); ``` ### Response Example ```json "$2b$10$N9qo8uLOickgx2ZMRZoMye7j.5s.jA9o.jJ8a2J6Lq7o0o3jJj5j" ``` ## bcrypt.genSalt (async with Callback) ### Description Asynchronously generates a salt using a callback function. ### Method `bcrypt.genSalt(rounds?: number, callback: Callback): void` ### Parameters - **rounds** (number) - Optional - Number of rounds to use for salt generation. Defaults to 10. - **callback** (Callback) - Required - The callback function to handle the result. It receives an error or the generated salt. ### Request Example ```javascript bcrypt.genSalt(10, (err, salt) => { if (err) { console.error(err); } else { console.log(salt); } }); ``` ### Response Example (Callback provides the result) ``` -------------------------------- ### Auto-generate salt and hash password asynchronously with await in TypeScript Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md Automatically generates salt and hashes password asynchronously with await. Input is password and rounds; output is hash promise. Non-blocking and simple, but subject to 72-byte input limit and slower than C++ version. ```typescript await bcrypt.hash("B4c0\/\/", 10); // Store hash in your password DB ``` -------------------------------- ### Auto-generate salt and hash password asynchronously with callback in TypeScript Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md Hashes password with auto-salt using callback. Input is password, rounds, and callback; output is hash via callback. Asynchronous via callbacks, optimized for event loop, with inherent input length checks. ```typescript bcrypt.hash("B4c0\/\/", 10, (err, hash) => { // Store hash in your password DB }); ``` -------------------------------- ### Generate salt and hash password asynchronously with await in TypeScript Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md Asynchronously generates a salt and hashes a password using await. Input is password and salt; output is the hash promise. Non-blocking, ideal for Node.js, but relies on event loop yielding for performance. ```typescript const salt = await bcrypt.genSalt(10); const hash = await bcrypt.hash("B4c0\/\/", salt); // Store hash in your password DB ``` -------------------------------- ### Password Comparison Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md Functions for comparing passwords against hashes, both synchronously and asynchronously. ```APIDOC ## bcrypt.compareSync ### Description Synchronously tests a password against a hash. ### Method `bcrypt.compareSync(password: string, hash: string): boolean` ### Parameters - **password** (string) - Required - The password to compare. - **hash** (string) - Required - The hash to compare against. ### Response - **boolean** - True if the password matches the hash, false otherwise. ### Request Example ```javascript const isMatch = bcrypt.compareSync('mysecretpassword', '$2b$10$N9qo8uLOickgx2ZMRZoMye7j.5s.jA9o.jJ8a2J6Lq7o0o3jJj5j'); console.log(isMatch); ``` ### Response Example ```json true ``` ## bcrypt.compare (async with Promise) ### Description Asynchronously compares a password against a hash using Promises. ### Method `bcrypt.compare(password: string, hash: string): Promise` ### Parameters - **password** (string) - Required - The password to compare. - **hash** (string) - Required - The hash to compare against. ### Response - **Promise** - A promise that resolves with true if the password matches the hash, false otherwise. ### Request Example ```javascript bcrypt.compare('mysecretpassword', '$2b$10$N9qo8uLOickgx2ZMRZoMye7j.5s.jA9o.jJ8a2J6Lq7o0o3jJj5j').then(isMatch => { console.log(isMatch); }); ``` ### Response Example ```json true ``` ## bcrypt.compare (async with Callback) ### Description Asynchronously compares a password against a hash using a callback function. ### Method `bcrypt.compare(password: string, hash: string, callback: Callback, progressCallback?: ProgressCallback): void` ### Parameters - **password** (string) - Required - The password to compare. - **hash** (string) - Required - The hash to compare against. - **callback** (Callback) - Required - The callback function to handle the result. It receives an error or a boolean indicating if the password matches. - **progressCallback** (ProgressCallback) - Optional - A callback function to report progress during comparison. ### Request Example ```javascript bcrypt.compare('mysecretpassword', '$2b$10$N9qo8uLOickgx2ZMRZoMye7j.5s.jA9o.jJ8a2J6Lq7o0o3jJj5j', (err, isMatch) => { if (err) { console.error(err); } else { console.log(isMatch); } }, percentage => { console.log(`Comparison progress: ${percentage * 100}%`); }); ``` ### Response Example (Callback provides the result) ``` -------------------------------- ### Synchronous Password Comparison with bcrypt.js Source: https://context7.com/dcodeio/bcrypt.js/llms.txt Shows how to synchronously compare a plaintext password against a stored hash using bcrypt.js's `compareSync` method. This method uses constant-time comparison to prevent timing attacks. It's suitable for environments where blocking the event loop is acceptable or for specific synchronous tasks. Requires the 'bcryptjs' package. ```javascript import bcrypt from "bcryptjs"; // Create a hash const password = "myPassword123"; const hash = bcrypt.hashSync(password, 10); // Compare passwords const isValid = bcrypt.compareSync("myPassword123", hash); console.log(isValid); // true const isInvalid = bcrypt.compareSync("wrongPassword", hash); console.log(isInvalid); // false // Real-world login validation function validateLogin(inputPassword, storedHash) { try { const isMatch = bcrypt.compareSync(inputPassword, storedHash); if (isMatch) { console.log("Login successful"); return { success: true }; } else { console.log("Invalid credentials"); return { success: false, error: "Invalid password" }; } } catch (error) { console.error("Comparison error:", error); return { success: false, error: "Authentication error" }; } } // Usage in authentication const storedHash = "$2b$10$N9qo8uLOickgx2ZMRZoMye..."; const result = validateLogin("userInput123", storedHash); ``` -------------------------------- ### Generate Synchronous Salt with bcryptjs Source: https://context7.com/dcodeio/bcrypt.js/llms.txt Creates a cryptographically secure salt using bcrypt.genSaltSync with optional round specification. The generated salt can be used for hashing passwords. This method blocks the event loop and is suitable for initialization phases. ```JavaScript import bcrypt from "bcryptjs"; // Generate salt with default 10 rounds const salt = bcrypt.genSaltSync(); console.log(salt); // "$2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcg7b3..." // Generate salt with 12 rounds (more secure, slower) const secureSalt = bcrypt.genSaltSync(12); console.log(secureSalt); // "$2b$12$..." // Use the salt for hashing const password = "mySecurePassword123"; const hash = bcrypt.hashSync(password, salt); ``` -------------------------------- ### Generate salt and hash password synchronously in TypeScript Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md This code generates a salt synchronously and hashes a password using it. Input is the password string and salt rounds; output is the hashed string. It uses synchronous methods, blocking execution, and limits input to 72 bytes. ```typescript const salt = bcrypt.genSaltSync(10); const hash = bcrypt.hashSync("B4c0\/\/", salt); // Store hash in your password DB ``` -------------------------------- ### Password Hashing Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md Functions for hashing passwords, both synchronously and asynchronously. ```APIDOC ## bcrypt.hashSync ### Description Synchronously generates a hash for the given password. ### Method `bcrypt.hashSync(password: string, salt?: number | string): string` ### Parameters - **password** (string) - Required - The password to hash. - **salt** (number | string) - Optional - The salt to use for hashing. If a number is provided, it represents the number of rounds. If omitted, defaults to 10 rounds. ### Response - **string** - The generated hash. ### Request Example ```javascript const hash = bcrypt.hashSync('mysecretpassword', 10); ``` ### Response Example ```json "$2b$10$N9qo8uLOickgx2ZMRZoMye7j.5s.jA9o.jJ8a2J6Lq7o0o3jJj5j" ``` ## bcrypt.hash (async with Promise) ### Description Asynchronously generates a hash for the given password using Promises. ### Method `bcrypt.hash(password: string, salt: number | string): Promise` ### Parameters - **password** (string) - Required - The password to hash. - **salt** (number | string) - Required - The salt to use for hashing. Can be a salt string or the number of rounds. ### Response - **Promise** - A promise that resolves with the generated hash. ### Request Example ```javascript bcrypt.hash('mysecretpassword', '$2b$10$N9qo8uLOickgx2ZMRZoMye7j').then(hash => { console.log(hash); }); ``` ### Response Example ```json "$2b$10$N9qo8uLOickgx2ZMRZoMye7j.5s.jA9o.jJ8a2J6Lq7o0o3jJj5j" ``` ## bcrypt.hash (async with Callback) ### Description Asynchronously generates a hash for the given password using a callback function. ### Method `bcrypt.hash(password: string, salt: number | string, callback: Callback, progressCallback?: ProgressCallback): void` ### Parameters - **password** (string) - Required - The password to hash. - **salt** (number | string) - Required - The salt to use for hashing. Can be a salt string or the number of rounds. - **callback** (Callback) - Required - The callback function to handle the result. It receives an error or the generated hash. - **progressCallback** (ProgressCallback) - Optional - A callback function to report progress during hashing. ### Request Example ```javascript bcrypt.hash('mysecretpassword', 10, (err, hash) => { if (err) { console.error(err); } else { console.log(hash); } }, percentage => { console.log(`Hashing progress: ${percentage * 100}%`); }); ``` ### Response Example (Callback provides the result) ``` -------------------------------- ### Other Functions Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md Miscellaneous functions like testing password truncation. ```APIDOC ## bcrypt.truncates ### Description Tests if a password will be truncated when hashed, that is its length is greater than 72 bytes when converted to UTF-8. ### Method `bcrypt.truncates(password: string): boolean` ### Parameters - **password** (string) - Required - The password to test. ### Response - **boolean** - True if the password will be truncated, false otherwise. ### Request Example ```javascript const willTruncate = bcrypt.truncates('a_very_long_password_that_will_definitely_be_truncated_when_hashed_with_bcrypt_due_to_its_length_limitations'); console.log(willTruncate); ``` ### Response Example ```json true ``` ``` -------------------------------- ### Hash password asynchronously with callback in TypeScript Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md Hashes a password asynchronously using callback functions. Input is password, salt, and callback; output is hash via callback. Uses callback pattern for Node.js compatibility, with operation split into chunks for yielding. ```typescript bcrypt.genSalt(10, (err, salt) => { bcrypt.hash("B4c0\/\/", salt, function (err, hash) { // Store hash in your password DB }); }); ``` -------------------------------- ### Generate Asynchronous Salt with bcryptjs Source: https://context7.com/dcodeio/bcrypt.js/llms.txt Asynchronously creates a salt using bcrypt.genSalt, available via Promise or callback interfaces to avoid blocking the event loop. It defaults to 10 rounds if not specified. The generated salt can be directly used for password hashing. ```JavaScript import bcrypt from "bcryptjs"; // Promise-based usage async function generateSalt() { try { const salt = await bcrypt.genSalt(10); console.log("Generated salt:", salt); return salt; } catch (error) { console.error("Salt generation failed:", error); } } // Callback-based usage bcrypt.genSalt(10, (err, salt) => { if (err) { console.error("Error:", err); return; } console.log("Salt:", salt); // Use salt for hashing... }); // Omitting rounds defaults to 10 bcrypt.genSalt((err, salt) => { console.log("Salt with default rounds:", salt); }); ``` -------------------------------- ### Auto-generate salt and hash password synchronously in TypeScript Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md Automatically generates a salt and hashes the password synchronously. Input is password and salt rounds; output is the hash. Suitable for simple use cases but blocking, with input length limitations applied internally. ```typescript const hash = bcrypt.hashSync("bacon", 10); ``` -------------------------------- ### Compare passwords asynchronously with callback in TypeScript Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md Verifies passwords asynchronously using callbacks. Input is password, hash, and callback; output is result via callback. Callback-based, compatible with legacy Node.js, with chunked processing to avoid blocking. ```typescript // Load hash from your password DB bcrypt.compare("B4c0\/\/", hash, (err, res) => { // res === true }); bcrypt.compare("not_bacon", hash, (err, res) => { // res === false }); ``` -------------------------------- ### Compare passwords asynchronously with await in TypeScript Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md Asynchronously verifies passwords against a hash using await. Input is plain password and hash; output is boolean promise. Non-blocking, efficient for web environments, but may yield performance in compute-intensive tasks. ```typescript // Load hash from your password DB await bcrypt.compare("B4c0\/\/", hash); // true await bcrypt.compare("not_bacon", hash); // false ``` -------------------------------- ### Compare passwords synchronously in TypeScript Source: https://github.com/dcodeio/bcrypt.js/blob/main/README.md This snippet shows synchronous password verification against a stored hash. Input is the plain password and hash; output is a boolean result. It blocks execution and assumes the input password length is checked separately. ```typescript // Load hash from your password DB bcrypt.compareSync("B4c0\/\/", hash); // true bcrypt.compareSync("not_bacon", hash); // false ``` -------------------------------- ### Encode Bytes to Bcrypt Base64 (JavaScript) Source: https://context7.com/dcodeio/bcrypt.js/llms.txt Encodes a byte array into a string using bcrypt's custom base64 alphabet. This function is primarily for internal use but can be utilized for advanced scenarios. It takes a byte array and its length as input, returning the encoded string. ```javascript import bcrypt from "bcryptjs"; // Encode byte array to bcrypt base64 const bytes = [72, 101, 108, 108, 111]; // "Hello" in ASCII const encoded = bcrypt.encodeBase64(bytes, bytes.length); console.log(encoded); // Bcrypt-style base64 string // Example with binary data const binaryData = new Uint8Array([0x00, 0xFF, 0x80, 0x7F]); const encodedBinary = bcrypt.encodeBase64(binaryData, binaryData.length); console.log(encodedBinary); // Round-trip encoding/decoding function testRoundTrip(data) { const encoded = bcrypt.encodeBase64(data, data.length); const decoded = bcrypt.decodeBase64(encoded, data.length); const match = data.every((byte, i) => byte === decoded[i]); console.log(`Round trip ${match ? "successful" : "failed"}`); return { original: data, encoded, decoded, match }; } testRoundTrip([1, 2, 3, 4, 5]); // Round trip successful // { original: [1,2,3,4,5], encoded: "...", decoded: [1,2,3,4,5], match: true } ``` -------------------------------- ### Decode Bcrypt Base64 to Bytes (JavaScript) Source: https://context7.com/dcodeio/bcrypt.js/llms.txt Decodes a bcrypt base64-encoded string back into a byte array. This function is essential for interpreting data encoded with bcrypt's specific base64 alphabet, which differs from standard base64. It requires the encoded string and the expected byte length. ```javascript import bcrypt from "bcryptjs"; // Decode bcrypt base64 string const encoded = "N9qo8uLOickgx2ZMRZoMye"; const decoded = bcrypt.decodeBase64(encoded, 16); console.log(decoded); // Array of byte values // Extract and decode salt from hash function analyzeSalt(hash) { const saltPortion = hash.substring(7, 29); // Skip "$2b$10$" const decodedSalt = bcrypt.decodeBase64(saltPortion, 16); console.log("Hash:", hash); console.log("Salt string:", saltPortion); console.log("Salt bytes:", decodedSalt); console.log("Salt length:", decodedSalt.length); return decodedSalt; } const hash = bcrypt.hashSync("password", 10); const saltBytes = analyzeSalt(hash); // Compare with standard base64 function compareBcryptVsStandardBase64() { const data = [1, 2, 3, 4, 5]; // Bcrypt encoding const bcryptEncoded = bcrypt.encodeBase64(data, data.length); // Standard base64 (for comparison) const buffer = Buffer.from(data); const standardBase64 = buffer.toString("base64"); console.log("Bcrypt base64: ", bcryptEncoded); console.log("Standard base64:", standardBase64); console.log("Are different: ", bcryptEncoded !== standardBase64); } compareBcryptVsStandardBase64(); ``` -------------------------------- ### Check Password Length Validity for bcrypt Hashing - JavaScript Source: https://context7.com/dcodeio/bcrypt.js/llms.txt Tests if a password exceeds the 72-byte UTF-8 limit, which would cause it to be truncated during bcrypt hashing. This is crucial for validating user input to prevent potential security issues or unexpected behavior. It takes a password string as input and returns a boolean. ```javascript import bcrypt from "bcryptjs"; // Test various password lengths const shortPass = "password123"; const longPass = "a".repeat(73); const unicodePass = "🔒".repeat(20); // Multi-byte characters console.log(bcrypt.truncates(shortPass)); // false console.log(bcrypt.truncates(longPass)); // true console.log(bcrypt.truncates(unicodePass)); // true (emojis are 4 bytes each) // Real-world validation function function validatePasswordLength(password) { if (bcrypt.truncates(password)) { return { valid: false, error: "Password exceeds 72 bytes when UTF-8 encoded", suggestion: "Use a shorter password or fewer special characters" }; } return { valid: true }; } // Express.js middleware function passwordValidationMiddleware(req, res, next) { const { password } = req.body; if (!password) { return res.status(400).json({ error: "Password required" }); } if (bcrypt.truncates(password)) { return res.status(400).json({ error: "Password too long (max 72 bytes UTF-8)" }); } next(); } app.post("/api/register", passwordValidationMiddleware, async (req, res) => { // Password is guaranteed to be within valid length const hash = await bcrypt.hash(req.body.password, 10); // ... }); // Interactive validation function checkPassword(password) { const willTruncate = bcrypt.truncates(password); const byteLength = new TextEncoder().encode(password).length; console.log(`Password: "${password}"`); console.log(`Byte length: ${byteLength}`); console.log(`Will truncate: ${willTruncate}`); return !willTruncate; } checkPassword("short"); // Byte length: 5, Will truncate: false checkPassword("x".repeat(100)); // Byte length: 100, Will truncate: true ``` -------------------------------- ### Extract Salt from bcrypt Hash - JavaScript Source: https://context7.com/dcodeio/bcrypt.js/llms.txt Extracts the salt portion from a bcrypt hash. The salt is the first 29 characters of the hash string. This function does not validate the hash format itself. It takes the hash string as input and returns the salt string. Dependencies: bcryptjs. ```javascript import bcrypt from "bcryptjs"; // Generate hash const password = "testPassword"; const hash = bcrypt.hashSync(password, 10); console.log(hash); // "$2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcg7b3XeKeUxWdeS86E36P6YULE" // Extract salt const salt = bcrypt.getSalt(hash); console.log(salt); // "$2b$10$N9qo8uLOickgx2ZMRZoMye" // Verify salt length (should be 29 characters) console.log(salt.length); // 29 // Practical example: Salt reuse detection function detectSaltReuse(hashes) { const salts = new Set(); const reused = []; for (const hash of hashes) { const salt = bcrypt.getSalt(hash); if (salts.has(salt)) { reused.push(salt); } salts.add(salt); } if (reused.length > 0) { console.warn("Warning: Salt reuse detected!"); return { secure: false, reusedSalts: reused }; } return { secure: true }; } // Check multiple hashes const hashes = [ bcrypt.hashSync("pass1", 10), bcrypt.hashSync("pass2", 10), bcrypt.hashSync("pass3", 10) ]; const analysis = detectSaltReuse(hashes); console.log(analysis); // { secure: true } ``` -------------------------------- ### Extract Round Count from bcrypt Hash - JavaScript Source: https://context7.com/dcodeio/bcrypt.js/llms.txt Extracts the number of rounds used to generate a bcrypt hash. This is useful for checking if a hash needs to be rehashed with a higher number of rounds for improved security. It takes the hash string as input and returns the round count as an integer. Dependencies: bcryptjs. ```javascript import bcrypt from "bcryptjs"; // Create hashes with different rounds const hash10 = bcrypt.hashSync("password", 10); const hash12 = bcrypt.hashSync("password", 12); // Extract rounds const rounds1 = bcrypt.getRounds(hash10); console.log(rounds1); // 10 const rounds2 = bcrypt.getRounds(hash12); console.log(rounds2); // 12 // Practical use: Rehashing strategy async function checkAndRehash(password, currentHash, targetRounds = 12) { const currentRounds = bcrypt.getRounds(currentHash); // Verify current password const isValid = await bcrypt.compare(password, currentHash); if (!isValid) { return { error: "Invalid password" }; } // Rehash if using outdated rounds if (currentRounds < targetRounds) { console.log(`Upgrading from ${currentRounds} to ${targetRounds} rounds`); const newHash = await bcrypt.hash(password, targetRounds); return { rehashed: true, newHash }; } return { rehashed: false }; } // Usage in login flow const result = await checkAndRehash("userPassword", "$2b$10$...", 12); if (result.rehashed) { // Update database with result.newHash console.log("Password security upgraded"); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.