← Back to Chapters

Password Hashing

? Password Hashing

? Quick Overview

The md5() and sha1() functions are used in PHP to generate hash values from input strings. These hash functions are often used for data integrity verification, password storage, and generating unique identifiers for data.

? Key Concepts

  • md5() – Generates a 128-bit hash value for a given string. It is commonly used for hashing passwords and data integrity checks.
  • sha1() – Generates a 160-bit hash value. It is stronger than MD5 and provides more security, though it is still not suitable for cryptographic security purposes.

? Syntax & Theory

Hashing converts plain text into a fixed-length string. Modern PHP applications should use password_hash() and password_verify() because they automatically handle salting and stronger algorithms.

? Example 1: Using md5()

md5() returns a 32-character hexadecimal representation of the hash value of a string.

? View Code Example
// Generate an MD5 hash from a string
<?php
$string = "Hello, World!";
$md5_hash = md5($string);
echo $md5_hash;
?>

? Explanation

The string "Hello, World!" is passed to md5(). The output is always a 32-character hexadecimal hash representing the original string.

? Example 2: Using sha1()

sha1() returns a 40-character hexadecimal representation of the hash value.

? View Code Example
// Generate a SHA1 hash from a string
<?php
$string = "Hello, World!";
$sha1_hash = sha1($string);
echo $sha1_hash;
?>

? Explanation

The sha1() function produces a longer hash than MD5, making it slightly stronger, but still not recommended for secure password storage.

⚙️ Secure Password Hashing Example

? View Code Example
// Secure password hashing and verification using built-in PHP functions
<?php
$password = "mypassword123";
$hash = password_hash($password, PASSWORD_DEFAULT);

if (password_verify("mypassword123", $hash)) {
    echo "Password Verified";
} else {
    echo "Invalid Password";
}
?>

? Live Output / Explanation

If the entered password matches the stored hash, the message Password Verified is displayed. This method is secure and resistant to brute-force attacks.

? Use Cases

  • Storing user passwords securely in databases
  • Validating login credentials
  • Generating irreversible hashes for sensitive data

✅ Tips & Best Practices

  • Use password_hash() instead of MD5 or SHA1 for passwords.
  • Never store plain text passwords.
  • Let PHP manage salting and algorithm updates automatically.

? Try It Yourself

  • Create a signup form that stores hashed passwords.
  • Build a login system using password_verify().
  • Compare hash outputs for different passwords.