Blog | G5 Cyber Security

BCrypt Password Hashing: Email as Salt?

TL;DR

Using a user’s email address directly as a salt for BCrypt is not recommended. While it seems convenient, it creates significant security vulnerabilities. A proper salt should be random and unique per password. This guide explains why, and shows how to use a secure approach with Python.

Why Email as Salt is Bad

Here’s why using an email address as a salt for BCrypt hashing is problematic:

Secure Password Hashing with BCrypt

The correct approach is to use a randomly generated salt for each password and store the salt alongside the hash.

Step-by-Step Guide (Python Example)

  1. Install Required Libraries:
  2. pip install bcrypt
  3. Generate a Random Salt: BCrypt handles salt generation for you. You don’t need to create it manually.
  4. Hash the Password: Use the bcrypt.hashpw() function. This automatically generates a random salt and combines it with the password before hashing.
  5. import bcrypt
    
    def hash_password(password):
        # Generate a salt and hash the password
        hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
        return hashed.decode('utf-8')
    
  6. Store the Hash: Store the hashed value (as a string) in your database, along with the user’s email address (but *not* as part of the hash).
  7. Verify the Password: Use the bcrypt.checkpw() function to compare the entered password with the stored hash. BCrypt automatically extracts the salt from the stored hash for verification.
    def verify_password(password, hashed):
        # Verify the password against the stored hash
        return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))
    
  8. Example Usage:
  9. user_email = "test@example.com"
    plain_text_password = "mysecretpassword"
    
    # Hash the password
    hashed_password = hash_password(plain_text_password)
    print(f"Hashed Password for {user_email}: {hashed_password}")
    
    # Verify the password
    if verify_password(plain_text_password, hashed_password):
        print("Password verified!")
    else:
        print("Incorrect password.")
    
  10. Important Considerations:

In Summary

Never use user-provided data like email addresses directly as salts for password hashing. Always rely on BCrypt’s built-in salt generation and secure verification mechanisms.

Exit mobile version