Blog | G5 Cyber Security

Secure User Authentication

TL;DR

Storing usernames (emails) and passwords together in a single hashed field is insecure. This guide explains how to separate them, hash each individually with strong algorithms, and store the hashes securely for better cyber security.

Solution Guide: Separating & Hashing User Credentials

  1. Understand the Risk
  • Database Schema Change
  • Modify your database to store usernames (emails) and password hashes in separate columns.

  • Choose a Strong Hashing Algorithm
  • Use modern, robust password hashing algorithms. Avoid older algorithms like MD5 and SHA1.

  • Hashing Passwords on Registration
  • When a new user registers, hash their password before storing it in the database.

    # Example using Python and bcrypt
    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_user_password = "MySecurePassword123"
    hashed_password = hash_password(new_user_password)
    print(hashed_password) # Store this in the password_hash column
    
  • Verifying Passwords on Login
  • When a user logs in, retrieve their stored password_hash and compare it to the hash of the entered password.

    # Example using Python and bcrypt
    import bcrypt
    
    def verify_password(entered_password, stored_hash):
        return bcrypt.checkpw(entered_password.encode('utf-8'), stored_hash.encode('utf-8'))
    
    # Example usage:
    stored_hash = "$2b$12$EXAMPLEHASHEDPASSWORD"
    user_entered_password = "MySecurePassword123"
    is_valid = verify_password(user_entered_password, stored_hash)
    print(is_valid) # True if the password matches
    
  • Salting (if not using bcrypt/Argon2)
  • If your chosen algorithm doesn’t handle salting automatically, you must add a unique salt to each password before hashing.

  • Security Considerations
  • Exit mobile version