DEV Community

Jae Jeong
Jae Jeong

Posted on

Securing Passwords in User Authentication

Introduction

When passwords are saved as plaintext, there is a huge risk of the password being exposed in a data breach. In order to make it difficult for hackers from obtaining such data, password hashes and salting are concepts used in securing passwords.

Password Hashes

A password hash is a string of fixed length that is generated by a hash function from a password. Hashing transforms a given password into a unique representation that is stored in place of a plaintext password. Hashing is a one-way operation which makes it difficult for hackers to reverse-engineer the original password. An analogy for the hashing process is making a smoothie. All the ingredients can be blended into a smoothie, but the process cannot be reversed to obtain fruits from a smoothie.

Salting

A salt is a random string added to the password before it is hashed. Each password has a unique salt. Salting prevents attackers from using precomputed hash tables (also known as rainbow tables) to crack passwords. This means that even if two users have the same password, their hashed passwords will be different because each has a unique salt.

Bcrypt

Bcrypt is a popular library that is used to secure user passwords. It utilizes hashing and salting through a cryptographic algorithm to scramble a user's password into a unique string. Whenever a user logs in, the inputted password is re-hashed with the unique salt and compared to the stored password.

Using Bcrypt in Python

import bcrypt

# Hash Function
def hash_password(password):
    # Generate a salt
    salt = bcrypt.gensalt()

    # Hash the password with the salt
    hashed_password = bcrypt.hashpw(password.encode("utf-8"), salt)

    return hashed_password

# Example Usage
password = "password"
hashed = hash_password(password)
print(hashed)
# returns $2b$12$zN6GSrAJGHu5ERqjHQUBOugzdHwLpR7jOiTwGE.G0LEv8.OxBNREm
Enter fullscreen mode Exit fullscreen mode

Conclusion

Plaintext passwords are a huge risk in data breaches. Password hashing and salting are crucial in maintaining user security. Bcrypt is a popular library used to secure passwords. Other popular libraries include scrypt or Argon2.

Top comments (0)