Blog | G5 Cyber Security

BCrypt Hashing 6-Digit Numbers

TL;DR

This guide shows you how to securely store six-digit numbers (000000 – 999999) using BCrypt hashing. We’ll cover generating the hashes, verifying them, and important security considerations.

Generating BCrypt Hashes

  1. Choose a Library: You’ll need a BCrypt library for your programming language. Common options include:
    • Python: bcrypt
    • PHP: password_hash() (built-in)
    • Node.js: bcryptjs
    • Java: BCrypt from jBCrypt
  2. Install the Library: Use your package manager to install the chosen library.
    • Python (pip):
      pip install bcrypt
    • Node.js (npm):
      npm install bcryptjs
  3. Hash the Number: Convert the number to a string, then use the library’s hashing function.

    Important: Always hash strings. Do not attempt to directly hash integers.

    Example (Python):

    import bcrypt
    
    def hash_number(number):
      number_str = str(number)
      hashed = bcrypt.hashpw(number_str.encode('utf-8'), bcrypt.gensalt())
      return hashed.decode('utf-8')
    
    # Example usage:
    number_to_hash = 123456
    hash = hash_number(number_to_hash)
    print(f"The hash for {number_to_hash} is: {hash}")

    Example (PHP):

    Note: bcrypt.gensalt() (Python) and PASSWORD_DEFAULT (PHP) automatically handle the salt generation, which is crucial for security.

Verifying BCrypt Hashes

  1. Use the Library’s Verification Function: Most libraries provide a function to compare a plain-text number with its hash.

    Example (Python):

    def verify_number(number, hashed):
      number_str = str(number)
      return bcrypt.checkpw(number_str.encode('utf-8'), hashed.encode('utf-8'))
    
    # Example usage:
    number_to_verify = 123456
    hash_to_verify = hash # The hash generated earlier
    if verify_number(number_to_verify, hash_to_verify):
      print("Password matches!")
    else:
      print("Password does not match.")

    Example (PHP):

Security Considerations

  1. Never Store Plain-Text Numbers: Always store the BCrypt hash, *not* the original number.
  2. Salting is Automatic: The bcrypt algorithm automatically handles salting, making it very secure. Don’t try to implement your own salt generation.
  3. Cost Factor (Rounds): BCrypt uses a cost factor to determine how much computational effort is required to hash and verify passwords. Higher cost factors are more secure but slower. The default cost factor is usually sufficient, but you can increase it if needed.
  4. Regularly Update Libraries: Keep your BCrypt library updated to benefit from security patches.
  5. cyber security Best Practices: Implement other cyber security measures like input validation and rate limiting to protect against brute-force attacks.
Exit mobile version