Welcome to our comprehensive guide on Password Hashing in Python! This lesson is designed for both beginners and intermediates, so let's dive in! 🌊
Password Hashing is a process of converting plain text passwords into a form that can be securely stored in a database. The hashed password cannot be reversed to the original password, but if a user enters the correct password, we can check if its hash matches the stored hash.
Hashing passwords is crucial for security because it:
Python offers several libraries for password hashing, but for this lesson, we'll focus on hashlib. It's built-in, cross-platform, and secure.
Let's hash a password using hashlib.
import hashlib
password = "mysecretpassword"
hashed_password = hashlib.sha256(password.encode()).hexdigest()
print("Hashed Password:", hashed_password)Pro Tip: Always encode the password before hashing to ensure it's bytes, not a string.
To check a password, we hash the entered password and compare it with the stored hash.
entered_password = "mysecretpassword"
stored_password = "4c6dc78454e10ededaa3754cb0350c0d45d8d93e80f6649bf86fba858bb0fb9e"
if entered_password == stored_password:
print("Password is correct.")
else:
print("Incorrect password.")Quiz: Why do we need to encode a password before hashing in Python?
Why do we need to encode a password before hashing in Python?
Salted hashing adds a random string (salt) to the password before hashing, making it more secure. Here's an example:
import os
import hashlib
salt = os.urandom(16)
password = "mysecretpassword"
hashed_password = hashlib.sha256(salt + password.encode()).hexdigest() + salt.hexdigest()
print("Hashed Password:", hashed_password)Salted hashing makes it harder for attackers to find the same hash even if they have the same password.
That's all for our Password Hashing tutorial! Practice these concepts to strengthen your Python skills. Happy coding! 🦘🚀
Note: Always store salted hashes securely and never store plain text passwords.
Quiz: Why do we use salted hashing?
Why do we use salted hashing?