Blog | G5 Cyber Security

Secure Password Hashing

TL;DR

Don’t store passwords directly in your database! Use a strong hashing algorithm (like bcrypt or Argon2) with salts to protect them. This guide shows you how.

1. Why Not Just Store Passwords?

Storing passwords as plain text is incredibly dangerous. If your database gets hacked, all your users’ passwords are compromised. Hashing turns passwords into a one-way string of characters, making it much harder for attackers to get the original password even if they have access to the hash.

2. What is Hashing and Salting?

3. Choosing a Hashing Algorithm

Some hashing algorithms are better than others. Here’s what to consider:

For most applications, bcrypt is a good starting point. Argon2 is preferable if you have the resources to implement it correctly.

4. Implementing Password Hashing (Example using Python and bcrypt)

  1. Install the bcrypt library:
  2. pip install bcrypt
  3. Hashing a password when creating an account:
  4. import bcrypt
    
    def hash_password(password):
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt)
        return hashed_password.decode('utf-8')
    
    # Example usage:
    new_password = "MySecretPassword"
    hashed_password = hash_password(new_password)
    print(f"Hashed password: {hashed_password}")
  5. Verifying a password when logging in:
  6. def verify_password(password, hashed_password):
        return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))
    
    # Example usage:
    user_entered_password = "MySecretPassword"
    is_valid = verify_password(user_entered_password, hashed_password)
    print(f"Password is valid: {is_valid}")
  7. Storing the hash in your database: Store the hashed_password string in your database. Do *not* store the original password!

5. Important Security Considerations

Exit mobile version