Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Encrypting Passwords in PHP
Password encryption in PHP is crucial for securing user credentials. While older methods like MD5 and SHA-1 are vulnerable, modern PHP offers robust solutions including crypt() with SHA-256/SHA-512 and the newer password_hash() function.
Using SHA-256 and SHA-512 with crypt()
Due to Blowfish vulnerabilities before PHP 5.3.7, SHA-256 and SHA-512 are recommended alternatives. Both use a similar salt format − $5$ prefix for SHA-256 and $6$ prefix for SHA-512, with optional rounds parameter for multiple hashing ?
<?php
echo 'SHA-256 (no rounds): ' . crypt('password-to-encrypt', '$5$YourSaltyStringz$') . "<br>";
echo 'SHA-512 (with rounds): ' . crypt('password-to-encrypt', '$6$rounds=1000$YourSaltyStringz$') . "<br>";
?>
SHA-256 (no rounds): $5$YourSaltyStringz$td0INaoVoMPD4kieVrkGE67siKj3N8.HSff8ep0Ybs8 SHA-512 (with rounds): $6$rounds=1000$YourSaltyStringz$A5UHscsEbSnPnaV6PmSF5T/MQK.Wc3klA.18c.gXG5pD0PVYSVr/7xwRu1XJyn8XpiMDNRTvpJm5S8DkmSywz1
The salt is 16 characters long and allows more than alphanumeric characters. The resulting hashes contain the salt as part of the hash string.
Modern Approach with password_hash()
PHP 5.5+ introduced password_hash() which automatically handles salting and is the recommended method for password encryption ?
<?php
// Using default algorithm (currently bcrypt)
$hash1 = password_hash('mypassword', PASSWORD_DEFAULT);
echo "Default: " . $hash1 . "<br>";
// Using bcrypt with custom cost
$hash2 = password_hash('mypassword', PASSWORD_BCRYPT, ['cost' => 12]);
echo "Bcrypt: " . $hash2 . "<br>";
?>
Default: $2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi Bcrypt: $2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K
Password Verification
Use password_verify() to check passwords against their hashes ?
<?php
$password = 'mypassword';
$hash = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi';
if (password_verify($password, $hash)) {
echo "Password is correct!";
} else {
echo "Invalid password.";
}
?>
Password is correct!
Conclusion
While crypt() with SHA-256/SHA-512 provides secure hashing, password_hash() and password_verify() are the modern standard for password encryption in PHP, offering better security and easier implementation.
