Current Location: Home> Latest Articles> How to use PHP's crypt() function to implement a secure user authentication process to ensure that password protection is more reliable?

How to use PHP's crypt() function to implement a secure user authentication process to ensure that password protection is more reliable?

M66 2025-05-22

In modern web development, the security of user authentication is crucial. If the password protection is not in place, it is very likely to lead to user information leakage and bring immeasurable losses. PHP's built-in crypt() function provides strong support for password encryption. Combined with reasonable process design, it can greatly improve authentication security. This article will introduce in detail how to use crypt() to implement a safe and reliable user authentication process.

1. Understand the crypt() function

The crypt() function is based on Unix's encryption algorithm and is used to encrypt strings (usually passwords). Its core advantage is that it supports a variety of encryption algorithms, including Blowfish, SHA-256, SHA-512, etc., and comes with a salt value (salt) mechanism, which greatly enhances the security of passwords.

The function prototype is as follows:

 string crypt(string $password, string $salt);
  • $password is the clear text of the password to be encrypted.

  • $salt is the salt used for encryption, which can determine the encryption algorithm and complexity.

2. Design a safe user registration process

When registering a user, we need to encrypt the plain text password and store it in the database. Examples are as follows:

 <?php
// User-submitted plaintext password
$password = $_POST['password'];

// Generate a safe salt(by Blowfish As an example)
$salt = '$2y$12$' . substr(str_replace('+', '.', base64_encode(random_bytes(16))), 0, 22);

// use crypt() Encryption password
$hashedPassword = crypt($password, $salt);

// Will $hashedPassword Save to the database
// Example:mysqli or PDO Code simplified

echo "Encrypted password:$hashedPassword";
?>
  • The Blowfish algorithm is used here. $2y$ represents Blowfish, and 12 is the calculation cost. The larger the number, the safer it is, but the slower the calculation.

  • random_bytes(16) generates strong random numbers to ensure the randomness of salt.

3. Implement a secure login verification process

When the user logs in, he needs to verify that the entered password matches the password saved in the database. Note that the salt of crypt() is contained in the encryption result, so it can be reused:

 <?php
// Password entered by the user
$password = $_POST['password'];

// Hash password query from the database
$storedHash = /* Password hash obtained by query statement */;

// use相同盐值重新加密输入密码
$checkHash = crypt($password, $storedHash);

if (hash_equals($storedHash, $checkHash)) {
    // Verification passed
    echo "Login successfully";
} else {
    // Verification failed
    echo "用户名or密码错误";
}
?>
  • Use hash_equals() to perform time-safe comparisons to avoid time attacks.

  • As long as the input password is the same as the salt corresponding to the password hash in the database, the result of crypt() re-encryption should exactly match.

4. Comprehensive examples—User registration and login process

 <?php
// 连接数据库Example(use mysqli)
$mysqli = new mysqli("m66.net", "user", "password", "database");

// User registration
function registerUser($username, $password) {
    global $mysqli;

    $salt = '$2y$12$' . substr(str_replace('+', '.', base64_encode(random_bytes(16))), 0, 22);
    $hashedPassword = crypt($password, $salt);

    $stmt = $mysqli->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
    $stmt->bind_param("ss", $username, $hashedPassword);
    return $stmt->execute();
}

// User login verification
function loginUser($username, $password) {
    global $mysqli;

    $stmt = $mysqli->prepare("SELECT password FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->bind_result($storedHash);
    if (!$stmt->fetch()) {
        return false; // The user does not exist
    }
    $stmt->close();

    $checkHash = crypt($password, $storedHash);
    return hash_equals($storedHash, $checkHash);
}

// Example调用
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    if (isset($_POST['register'])) {
        if (registerUser($username, $password)) {
            echo "Registered successfully";
        } else {
            echo "Registration failed";
        }
    } elseif (isset($_POST['login'])) {
        if (loginUser($username, $password)) {
            echo "Login successfully";
        } else {
            echo "用户名or密码错误";
        }
    }
}
?>

5. Additional safety advice

  • Use HTTPS : Ensure the data transmission process is encrypted and prevent man-in-the-middle attacks.

  • Limit the number of login attempts : prevent brute force cracking.

  • Regularly update encryption costs : As hardware performance improves, the cost parameters of Blowfish are increased in a timely manner.

  • Password strength detection : The user is prompted to set a strong password when registering.

  • Avoid storing sensitive information in plain text .