password_needs_rehash

password_needs_rehash(string $hash, string|int|null $algo, array $options = []): bool

Password-hash upgrade detection: the stored hash string is self-describing metadata (parse the $2y$12$ prefix) - rehash on login when the algorithm or cost no longer matches; the third piece of the password family.

C C23

C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* parse the cost out of a bcrypt hash: $2y$12$... -> 12 */
static int bcrypt_cost(const char *hash) {
    const char *p = strchr(hash + 1, '$'); /* end of the algo id "2y" */
    return p != NULL ? atoi(p + 1) : -1;
}

int main(void) {
    const char *hash = "$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.";
    int cost = bcrypt_cost(hash);
    printf("%d\n", cost);                          /* 12 */
    printf("%d\n", cost != 12);                    /* policy at 12: no rehash */
    printf("%d\n", cost < 13);                     /* policy raised to 13: rehash */
    printf("%d\n", strncmp(hash, "$2y$", 4) != 0); /* 1 if the algo differs */
    return 0;
}
Output
12
0
1
0

C++ C++26

C++26
#include <cstdlib>
#include <iostream>
#include <string>

int main() {
    std::string hash = "$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.";
    int cost = std::atoi(hash.c_str() + hash.find('$', 1) + 1); // skip "2y"
    std::cout << std::boolalpha;
    std::cout << cost << "\n";
    std::cout << (cost != 12) << "\n";   // policy at 12: no rehash
    std::cout << (cost < 13) << "\n";    // policy raised to 13: rehash
    std::cout << (hash.rfind("$2y$", 0) != 0) << "\n"; // prefix mismatch: algo differs
    return 0;
}
Output
12
false
true
false

C# v11.0.100

v11.0.100
// Hand-written: prefix + cost comparison, mirroring the PHP logic
var hash = "$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.";
var parts = hash.Split('$');            // ["", "2y", "12", "..."]
var cost = int.Parse(parts[2]);
Console.WriteLine(cost);
Console.WriteLine(parts[1] != "2y" || cost != 12); // policy at 12: no rehash
Console.WriteLine(parts[1] != "2y" || cost < 13);  // policy raised to 13: rehash
Console.WriteLine(parts[1] != "2y");               // algo differs from bcrypt?
Output
12
False
True
False

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	hash := "$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC."
	parts := strings.Split(hash, "$")        // ["", "2y", "12", "..."]
	cost, _ := strconv.Atoi(parts[2])
	fmt.Println(cost)
	fmt.Println(parts[1] != "2y" || cost != 12) // policy at 12: no rehash
	fmt.Println(parts[1] != "2y" || cost < 13)  // policy raised to 13: rehash
	fmt.Println(parts[1] != "2y")               // algo differs from bcrypt?
}
Output
12
false
true
false

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        String hash = "$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.";
        String[] parts = hash.split("\\$");   // ["", "2y", "12", "..."]
        int cost = Integer.parseInt(parts[2]);
        System.out.println(cost);
        System.out.println(!parts[1].equals("2y") || cost != 12); // policy at 12
        System.out.println(!parts[1].equals("2y") || cost < 13);  // policy at 13
        System.out.println(!parts[1].equals("2y"));               // algo differs?
    }
}
Output
12
false
true
false

JavaScript v26.13.1

v26.13.1
// Other ecosystems re-implement the check by parsing the self-describing prefix
const hash = "$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.";
const [, ident, costS] = hash.split("$");
const cost = Number(costS);
console.log(cost);
console.log(ident !== "2y" || cost !== 12); // policy at 12: no rehash
console.log(ident !== "2y" || cost < 13);   // policy raised to 13: rehash
console.log(ident !== "2y");                // algo differs from bcrypt?
Output
12
false
true
false

PHP v8.6.0

v8.6.0
// The stored hash is self-describing metadata: $2y$12$... = bcrypt at cost 12
$hash = '$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.';
var_dump(password_needs_rehash($hash, PASSWORD_BCRYPT, ['cost' => 12])); // policy unchanged: keep
var_dump(password_needs_rehash($hash, PASSWORD_BCRYPT, ['cost' => 13])); // cost raised: rehash
var_dump(password_needs_rehash($hash, PASSWORD_ARGON2ID));                // algo changed: rehash
Output
bool(false)
bool(true)
bool(true)

Python v3.15.2

v3.15.2
# Hand-written: parse the self-describing prefix, compare with the policy
hash_ = "$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC."
_, ident, cost_s, _ = hash_.split("$", 3)   # ["", "2y", "12", "..."]
cost = int(cost_s)
print(cost)
print(ident != "2y" or cost != 12)  # policy at 12: no rehash
print(ident != "2y" or cost < 13)   # policy raised to 13: rehash
print(ident != "2y")                # algo differs from bcrypt?
Output
12
False
True
False

Rust v1.99.1

v1.99.1
fn main() {
    let hash = "$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.";
    let parts: Vec<&str> = hash.split('$').collect(); // ["", "2y", "12", "..."]
    let cost: u32 = parts[2].parse().unwrap();
    println!("{}", cost);
    println!("{}", parts[1] != "2y" || cost != 12); // policy at 12: no rehash
    println!("{}", parts[1] != "2y" || cost < 13);  // policy raised to 13: rehash
    println!("{}", parts[1] != "2y");               // algo differs from bcrypt?
}
Output
12
false
true
false

TypeScript v26.13.1

v26.13.1
// Same runtime as JS; the destructured shape stays explicit
const hash: string = "$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.";
const [, ident, costS]: string[] = hash.split("$");
const cost: number = Number(costS);
console.log(cost);
console.log(ident !== "2y" || cost !== 12);
console.log(ident !== "2y" || cost < 13);
console.log(ident !== "2y");
Output
12
false
true
false

Language differences

C: hand-written prefix parsing — the cost of $2y$12$... sits between the second and third $, and atoi extracts it for comparison with the policy; this is the universal cross-language idea.

C++: std::string::rfind(prefix, 0) checks a prefix (== 0 means hit); the cost is parsed from an offset with atoi.

C#: outside PHP, password_needs_rehash is usually handled by a framework (e.g. BCrypt.Net's NeedsRehash); hand-written, it is exactly prefix + cost comparison, mirroring the PHP logic line by line.

Go: stdlib has no password family; strings.Split(hash, "$") then compare parts[1]/parts[2] — in production use golang.org/x/crypto/bcrypt's CompareHashAndPassword for verification and compare against bcrypt.DefaultCost for upgrades.

Java: stdlib has no bcrypt (JDK only ships PBKDF2); the ecosystem uses Spring Security's BCryptPasswordEncoder or jBCrypt — a hand-written needs-rehash is prefix parsing.

JavaScript: bcrypt lives in npm packages (bcryptjs et al.); the counterpart of password_needs_rehash is parsing the cost and comparing it to the target, or a library helper like bcryptjs' getRounds(hash).

PHP: the third piece completing the password family (password_hash and password_verify have their own entries). Core lesson: the stored hash string is self-describing metadata — in $2y$12$..., $2y$ is the algorithm (bcrypt), 12 is the cost (a power-of-two work factor; +1 doubles the time), and the salt is encoded in the string itself, so nothing else needs storing. Typical migration flow: after password_verify succeeds, call password_needs_rehash — if true, re-hash with the new parameters and replace the old string in the database, upgrading users transparently at login. PASSWORD_DEFAULT is still bcrypt today, but pass the target algorithm and options explicitly instead of relying on the default drifting.

Python: the crypt module was removed in 3.13; the ecosystem uses the bcrypt/passlib packages. After bcrypt.checkpw, compare the parsed cost against the rounds of bcrypt.gensalt(rounds=N).

Rust: the bcrypt crate's verify only verifies; a needs-rehash is hand-written — parse the cost and compare with bcrypt::DEFAULT_COST (currently 12), or re-hash via bcrypt::hash_with_salt.

TypeScript: same runtime as JS; the type annotations make the destructured ident/cost shape explicit.