password_hash

password_hash(#[\SensitiveParameter] string $password, mixed $algo = PASSWORD_DEFAULT, array $options = []): string

Creates a one-way password hash (bcrypt by default: automatic random salt, deliberately slow); this entry demos the paired password_verify check on a fixed hash to keep output deterministic.

C C23

C23
#include <stdio.h>
#include <string.h>
#include "sha256.h" // vendored SHA-256 (Brad Conte, public domain)

// HMAC-SHA256 (RFC 2104) on top of the vendored SHA-256; key <= 64 bytes assumed
static void hmac_sha256(const BYTE *key, size_t keylen, const BYTE *msg, size_t msglen, BYTE out[32]) {
    BYTE k[64] = {0}, ipad[64], opad[64], inner[32];
    SHA256_CTX ctx;
    memcpy(k, key, keylen);
    for (int i = 0; i < 64; i++) {
        ipad[i] = k[i] ^ 0x36;
        opad[i] = k[i] ^ 0x5c;
    }
    sha256_init(&ctx);
    sha256_update(&ctx, ipad, 64);
    sha256_update(&ctx, msg, msglen);
    sha256_final(&ctx, inner);
    sha256_init(&ctx);
    sha256_update(&ctx, opad, 64);
    sha256_update(&ctx, inner, 32);
    sha256_final(&ctx, out);
}

// PBKDF2-HMAC-SHA256 (RFC 2898), single-block dkLen = 32 case
static void pbkdf2(const char *pass, const char *salt, int iters, BYTE out[32]) {
    BYTE u[32], t[32], msg[64];
    size_t passlen = strlen(pass), saltlen = strlen(salt);
    memcpy(msg, salt, saltlen);
    msg[saltlen] = 0;
    msg[saltlen + 1] = 0;
    msg[saltlen + 2] = 0;
    msg[saltlen + 3] = 1; // block index INT(1), big-endian
    hmac_sha256((const BYTE *)pass, passlen, msg, saltlen + 4, u);
    memcpy(t, u, 32);
    for (int i = 1; i < iters; i++) {
        hmac_sha256((const BYTE *)pass, passlen, u, 32, u);
        for (int j = 0; j < 32; j++) t[j] ^= u[j];
    }
    memcpy(out, t, 32);
}

static int verify(const char *password, const char *stored) {
    BYTE dk[32];
    char hex[65] = {0};
    pbkdf2(password, "codeabc-salt", 1000, dk);
    for (int i = 0; i < 32; i++) sprintf(hex + i * 2, "%02x", dk[i]);
    return strcmp(hex, stored) == 0; // demo compares strings; real code compares constant-time
}

int main(void) {
    const char *stored = "0a6eab55c375788ed4268a5e7d0ce7ea7ff56b1d3f3f10427763fa554d6b2bcd";
    printf("%s\n", verify("secret", stored) ? "true" : "false");
    printf("%s\n", verify("Secret", stored) ? "true" : "false");
    return 0;
}
Output
true
false

C++ C++26

C++26
#include <cstdio>
#include <cstring>
#include "sha256.h" // vendored SHA-256 (Brad Conte, public domain)

// HMAC-SHA256 (RFC 2104); key <= 64 bytes assumed
static void hmac_sha256(const BYTE *key, size_t keylen, const BYTE *msg, size_t msglen, BYTE out[32]) {
    BYTE k[64] = {0}, ipad[64], opad[64], inner[32];
    SHA256_CTX ctx;
    memcpy(k, key, keylen);
    for (int i = 0; i < 64; i++) {
        ipad[i] = k[i] ^ 0x36;
        opad[i] = k[i] ^ 0x5c;
    }
    sha256_init(&ctx);
    sha256_update(&ctx, ipad, 64);
    sha256_update(&ctx, msg, msglen);
    sha256_final(&ctx, inner);
    sha256_init(&ctx);
    sha256_update(&ctx, opad, 64);
    sha256_update(&ctx, inner, 32);
    sha256_final(&ctx, out);
}

// PBKDF2-HMAC-SHA256 (RFC 2898), single-block dkLen = 32 case
static void pbkdf2(const char *pass, const char *salt, int iters, BYTE out[32]) {
    BYTE u[32], t[32], msg[64];
    size_t passlen = strlen(pass), saltlen = strlen(salt);
    memcpy(msg, salt, saltlen);
    msg[saltlen] = 0;
    msg[saltlen + 1] = 0;
    msg[saltlen + 2] = 0;
    msg[saltlen + 3] = 1; // block index INT(1), big-endian
    hmac_sha256((const BYTE *)pass, passlen, msg, saltlen + 4, u);
    memcpy(t, u, 32);
    for (int i = 1; i < iters; i++) {
        hmac_sha256((const BYTE *)pass, passlen, u, 32, u);
        for (int j = 0; j < 32; j++) t[j] ^= u[j];
    }
    memcpy(out, t, 32);
}

static bool verify(const char *password, const char *stored) {
    BYTE dk[32];
    char hex[65] = {0};
    pbkdf2(password, "codeabc-salt", 1000, dk);
    for (int i = 0; i < 32; i++) sprintf(hex + i * 2, "%02x", dk[i]);
    return strcmp(hex, stored) == 0;
}

int main() {
    const char *stored = "0a6eab55c375788ed4268a5e7d0ce7ea7ff56b1d3f3f10427763fa554d6b2bcd";
    printf("%s\n", verify("secret", stored) ? "true" : "false");
    printf("%s\n", verify("Secret", stored) ? "true" : "false");
    return 0;
}
Output
true
false

C# v11.0.100

v11.0.100
using System.Security.Cryptography;
using System.Text;

// .NET has no built-in bcrypt; PBKDF2 (Rfc2898DeriveBytes.Pbkdf2) is the standard choice
byte[] stored = Convert.FromHexString("0a6eab55c375788ed4268a5e7d0ce7ea7ff56b1d3f3f10427763fa554d6b2bcd");
byte[] salt = Encoding.UTF8.GetBytes("codeabc-salt");

bool Verify(string password)
{
    byte[] candidate = Rfc2898DeriveBytes.Pbkdf2(password, salt, 1000, HashAlgorithmName.SHA256, 32);
    return CryptographicOperations.FixedTimeEquals(candidate, stored); // constant-time compare
}

Console.WriteLine(Verify("secret"));
Console.WriteLine(Verify("Secret"));
Output
True
False

Go v1.27.4

v1.27.4
package main

import (
    "fmt"

    "golang.org/x/crypto/bcrypt" // ecosystem standard; verifies PHP bcrypt hashes directly
)

func main() {
    hash := "$2y$12$/sXs8iV/A.GUMFTirj8h3e3P7mcfjPAEZHrPnCrNgff447C9eQthm"
    err := bcrypt.CompareHashAndPassword([]byte(hash), []byte("secret"))
    fmt.Println(err == nil) // nil error means the password matches
    err2 := bcrypt.CompareHashAndPassword([]byte(hash), []byte("Secret"))
    fmt.Println(err2 == nil)
}
Output
true
false

Java v27.0.1

v27.0.1
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class Main {
    // Java has no built-in bcrypt; PBKDF2WithHmacSHA256 is the standard choice
    static boolean verify(String password, byte[] stored) throws Exception {
        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(),
                "codeabc-salt".getBytes(StandardCharsets.UTF_8), 1000, 256);
        byte[] candidate = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
                .generateSecret(spec).getEncoded();
        return MessageDigest.isEqual(candidate, stored); // constant-time compare
    }

    public static void main(String[] args) throws Exception {
        byte[] stored = HexFormat.of().parseHex("0a6eab55c375788ed4268a5e7d0ce7ea7ff56b1d3f3f10427763fa554d6b2bcd");
        System.out.println(verify("secret", stored));
        System.out.println(verify("Secret", stored));
    }
}
Output
true
false

JavaScript v26.13.1

v26.13.1
const { pbkdf2Sync, timingSafeEqual } = require("node:crypto");

// Node has no built-in bcrypt; pbkdf2 (or scrypt) is the standard choice.
// stored digest was produced once with the same parameters.
const stored = Buffer.from("0a6eab55c375788ed4268a5e7d0ce7ea7ff56b1d3f3f10427763fa554d6b2bcd", "hex");

function verify(password) {
  const candidate = pbkdf2Sync(password, "codeabc-salt", 1000, 32, "sha256");
  return timingSafeEqual(candidate, stored); // constant-time, prevents timing attacks
}

console.log(verify("secret"));
console.log(verify("Secret"));
Output
true
false

PHP v8.6.0

v8.6.0
// password_hash() hashes with bcrypt and a random salt, so every call prints
// a different string; for a deterministic demo we verify a fixed hash instead
$hash = '$2y$12$/sXs8iV/A.GUMFTirj8h3e3P7mcfjPAEZHrPnCrNgff447C9eQthm';
var_dump(password_verify('secret', $hash)); // correct password
var_dump(password_verify('Secret', $hash)); // wrong password (case differs)
Output
bool(true)
bool(false)

Python v3.15.2

v3.15.2
import hashlib
import hmac

# Python has no built-in bcrypt; pbkdf2_hmac is the standard-library choice
stored = bytes.fromhex("0a6eab55c375788ed4268a5e7d0ce7ea7ff56b1d3f3f10427763fa554d6b2bcd")


def verify(password: str) -> bool:
    candidate = hashlib.pbkdf2_hmac("sha256", password.encode(), b"codeabc-salt", 1000)
    return hmac.compare_digest(candidate, stored)  # constant-time compare


print(verify("secret"))
print(verify("Secret"))
Output
True
False

Rust v1.99.1

v1.99.1
use bcrypt::verify; // bcrypt crate: ecosystem standard, verifies PHP hashes directly

fn main() {
    let hash = "$2y$12$/sXs8iV/A.GUMFTirj8h3e3P7mcfjPAEZHrPnCrNgff447C9eQthm";
    println!("{}", verify("secret", hash).unwrap_or(false));
    println!("{}", verify("Secret", hash).unwrap_or(false));
}
Output
true
false

TypeScript v26.13.1

v26.13.1
import { pbkdf2Sync, timingSafeEqual } from "node:crypto";

// stored digest produced once with the same PBKDF2 parameters
const stored: Buffer = Buffer.from(
  "0a6eab55c375788ed4268a5e7d0ce7ea7ff56b1d3f3f10427763fa554d6b2bcd",
  "hex",
);

function verify(password: string): boolean {
  const candidate = pbkdf2Sync(password, "codeabc-salt", 1000, 32, "sha256");
  return timingSafeEqual(candidate, stored); // constant-time compare
}

console.log(verify("secret"));
console.log(verify("Secret"));
Output
true
false

Language differences

C: hand-writes PBKDF2-HMAC over the vendored SHA-256 to reach the same value; real projects should use libsodium's argon2id instead of hand-rolling.

C++: same as C — hand-written PBKDF2-HMAC over the vendored SHA-256.

C#: the PBKDF2 route — built into .NET; identical parameters (SHA-256, 1000 rounds, same salt) yield the same hex across languages; comparisons use the constant-time FixedTimeEquals.

Go: the bcrypt route — golang.org/x/crypto/bcrypt verifies the $2y$ string produced by PHP directly (the Go example here verifies that same PHP string).

Java: the PBKDF2 route — built into the standard library; comparisons use the constant-time MessageDigest.isEqual.

JavaScript: the PBKDF2 route — built into Node; comparisons use the constant-time timingSafeEqual.

PHP: password_hash() defaults to bcrypt (PASSWORD_DEFAULT since PHP 5.5; still bcrypt in PHP 8.1+ with a smooth future switch to argon2id) — it generates a random salt automatically, paces itself deliberately, and embeds algorithm/cost/salt/checksum in one string ($2y$12$...), verified with the paired password_verify(); this entry does not demo a live password_hash() output because the random salt makes it non-deterministic — instead a fixed bcrypt string is verified; in real systems every user's hash differs (per-user random salt); why not md5/sha1/sha256 for passwords: they are too fast (GPUs try billions of candidates per second), making offline brute force trivial — password hashing must be deliberately slow or memory-hard; two mainstream routes are shown side by side: bcrypt (the PHP default, serializable + key-stretching iterations, GPU-resistant, cost factor 2^n upgradeable) and PBKDF2 (NIST-approved and the FIPS-world default, slowed by tunable iteration counts, weakest against GPUs but maximally compatible), with argon2 (the PHC winner, PASSWORD_ARGON2ID since PHP 7.2) as the more modern alternative; the two are equally legitimate choices — rolling your own "salted single hash" is never acceptable; security details: production parameters should exceed the demo values (OWASP: PBKDF2-HMAC-SHA256 >= 600,000 rounds, bcrypt cost >= 10).

Python: the PBKDF2 route — built into the standard library; comparisons use the constant-time hmac.compare_digest.

Rust: the bcrypt route — the bcrypt crate verifies the $2y$ string produced by PHP directly (the Rust example here verifies that same PHP string).

TypeScript: same as JS — Node PBKDF2 and timingSafeEqual.