What are the potential pitfalls or issues when storing passwords as SHA256 hashes in a database?
One potential pitfall of storing passwords as SHA256 hashes in a database is that it leaves the passwords vulnerable to dictionary attacks or brute force attacks. To mitigate this risk, it is recommended to use a salt in combination with the hashing algorithm. A salt is a randomly generated value that is unique for each password and is stored alongside the hash in the database.
// Generate a random salt
$salt = bin2hex(random_bytes(16));
// Combine the password and salt before hashing
$hashed_password = hash('sha256', $password . $salt);
// Store the hashed password and salt in the database
$stmt = $pdo->prepare("INSERT INTO users (username, password, salt) VALUES (?, ?, ?)");
$stmt->execute([$username, $hashed_password, $salt]);
Related Questions
- What is the difference between using explode and preg_split functions in PHP for string manipulation?
- How can authentication and login processes be securely implemented when scraping data from websites using PHP?
- How can a custom error handling function be implemented in PHP to send error messages via email?