This article was originally published on 2022-07-06 and migrated here from an old blog. Compiled by: Hermes
How to Encrypt Passwords During PHP Registration (Password Salt Encryption)
Secure storage of passwords is crucial during user registration and login. This article introduces how to encrypt passwords using a password salt (salt).
🔐 What is a Password Salt?
A password salt (Salt) is a random string combined with the password during hashing to prevent rainbow table attacks and ensure that identical passwords do not produce identical hash values.
📝 Encrypting Passwords During Registration
<?php
// Get username and password
$username = 'admin';
$password = "123456";
// Range for generating password salt
$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = strlen($str); // Length of the character set
$len = 5; // Set the length of the password salt
// Initialize password salt
$salt = substr(str_shuffle(str_repeat($str, ceil($len / strlen($str)))), 0, $len);
// Encrypt password: md5(md5(password) . salt)
$password = md5(md5($password) . $salt);
// Finally, store the username, encrypted password, and salt in the user table
// INSERT INTO users (username, password, salt) VALUES ('$username', '$password', '$salt');
?>🔑 Verifying Passwords During Login
<?php
// First, retrieve the encrypted password and salt from the database based on the username
$username = 'admin'; // Data transmitted from the frontend
$pwd = "123456"; // Data transmitted from the frontend
// Data retrieved from the database
$password = "8e934fc2152ddaa490159e39b7c7d7e6"; // Encrypted password
$salt = "NJnnz"; // Password salt
// Verify password
if (md5(md5($pwd) . $salt) == $password) {
echo "Login successful";
} else {
echo "Incorrect password";
}
?>📊 Encryption Flow Diagram
Registration:
User password → md5() → Add salt → md5() → Store in database
Login:
User enters password → md5() → Add salt (retrieved from database) → md5() → Compare with stored password⚠️ Security Recommendations
- Use stronger hashing algorithms: It is recommended to use
password_hash()andpassword_verify(). - Increase salt length: A random string of at least 16 characters is recommended.
- Use bcrypt: PHP's built-in
password_hash()uses bcrypt, which is more secure.
💡 Recommended Modern PHP Practices
<?php
// During registration
$password = password_hash($plainPassword, PASSWORD_BCRYPT);
// During login
if (password_verify($inputPassword, $storedHash)) {
// Login successful
}
?>Compiled by: Hermes