hash_pbkdf2
hash_pbkdf2(string $algo, string $password, string $salt, int $iterations, int $length = 0, bool $binary = false): string
Runs PBKDF2 key derivation and returns the key at the requested length as hex or binary.
C C23
#include <stdio.h>
#include <string.h>
#include "sha256.h"
// HMAC-SHA256 (RFC 2104): over-long keys are hashed first, then zero-padded
static void hmac_sha256(const BYTE *key, size_t klen, const BYTE *msg, size_t mlen, BYTE out[32]) {
BYTE k[64] = {0}, ipad[64], opad[64], inner[32];
if (klen > 64) {
SHA256_CTX c;
sha256_init(&c);
sha256_update(&c, key, klen);
sha256_final(&c, k);
} else {
memcpy(k, key, klen);
}
for (int i = 0; i < 64; i++) {
ipad[i] = k[i] ^ 0x36;
opad[i] = k[i] ^ 0x5c;
}
SHA256_CTX c;
sha256_init(&c);
sha256_update(&c, ipad, 64);
sha256_update(&c, msg, mlen);
sha256_final(&c, inner);
sha256_init(&c);
sha256_update(&c, opad, 64);
sha256_update(&c, inner, 32);
sha256_final(&c, out);
}
// PBKDF2 (RFC 2898): U1 = PRF(P, S || INT_BE(1)), XOR-accumulated round by round (single-block demo)
static void pbkdf2(const char *pass, const char *salt, int iter, BYTE dk[32]) {
BYTE msg[128], u[32], acc[32];
size_t slen = strlen(salt);
memcpy(msg, salt, slen);
msg[slen] = 0;
msg[slen + 1] = 0;
msg[slen + 2] = 0;
msg[slen + 3] = 1;
hmac_sha256((const BYTE *)pass, strlen(pass), msg, slen + 4, u);
memcpy(acc, u, 32);
for (int i = 1; i < iter; i++) {
hmac_sha256((const BYTE *)pass, strlen(pass), u, 32, u);
for (int j = 0; j < 32; j++) acc[j] ^= u[j];
}
memcpy(dk, acc, 32);
}
int main(void) {
BYTE dk[32];
pbkdf2("password", "salt", 1000, dk);
for (int i = 0; i < 8; i++) printf("%02x", dk[i]);
printf("\n");
return 0;
}
632c2812e46d4604
C++ C++26
#include <cstdio>
#include <cstring>
#include <iostream>
#include "sha256.h"
// HMAC-SHA256 (RFC 2104): over-long keys are hashed first, then zero-padded
static void hmac_sha256(const BYTE *key, size_t klen, const BYTE *msg, size_t mlen, BYTE out[32]) {
BYTE k[64] = {0}, ipad[64], opad[64], inner[32];
if (klen > 64) {
SHA256_CTX c;
sha256_init(&c);
sha256_update(&c, key, klen);
sha256_final(&c, k);
} else {
memcpy(k, key, klen);
}
for (int i = 0; i < 64; i++) {
ipad[i] = k[i] ^ 0x36;
opad[i] = k[i] ^ 0x5c;
}
SHA256_CTX c;
sha256_init(&c);
sha256_update(&c, ipad, 64);
sha256_update(&c, msg, mlen);
sha256_final(&c, inner);
sha256_init(&c);
sha256_update(&c, opad, 64);
sha256_update(&c, inner, 32);
sha256_final(&c, out);
}
// PBKDF2 (RFC 2898): U1 = PRF(P, S || INT_BE(1)), XOR-accumulated round by round (single-block demo)
static void pbkdf2(const char *pass, const char *salt, int iter, BYTE dk[32]) {
BYTE msg[128], u[32], acc[32];
size_t slen = strlen(salt);
memcpy(msg, salt, slen);
msg[slen] = 0;
msg[slen + 1] = 0;
msg[slen + 2] = 0;
msg[slen + 3] = 1;
hmac_sha256((const BYTE *)pass, strlen(pass), msg, slen + 4, u);
memcpy(acc, u, 32);
for (int i = 1; i < iter; i++) {
hmac_sha256((const BYTE *)pass, strlen(pass), u, 32, u);
for (int j = 0; j < 32; j++) acc[j] ^= u[j];
}
memcpy(dk, acc, 32);
}
int main() {
BYTE dk[32];
pbkdf2("password", "salt", 1000, dk);
char hex[17];
for (int i = 0; i < 8; i++) snprintf(hex + i * 2, 3, "%02x", dk[i]);
std::cout << hex << "\n";
return 0;
}
632c2812e46d4604
C# v11.0.100
using System.Security.Cryptography;
using System.Text;
// Rfc2898DeriveBytes: .NET's built-in PBKDF2 (salt as a byte array; GetBytes counts in bytes)
var derive1 = new Rfc2898DeriveBytes("password", Encoding.UTF8.GetBytes("salt"), 1000, HashAlgorithmName.SHA256);
Console.WriteLine(Convert.ToHexString(derive1.GetBytes(8)).ToLower());
var derive2 = new Rfc2898DeriveBytes("password", Encoding.UTF8.GetBytes("salt"), 1000, HashAlgorithmName.SHA256);
Console.WriteLine(Convert.ToHexString(derive2.GetBytes(32)).ToLower()[..16]);
632c2812e46d4604 632c2812e46d4604
Go v1.27.4
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"golang.org/x/crypto/pbkdf2"
)
func main() {
// x/crypto/pbkdf2 (not standard library, pulled via go get): keyLen counts in bytes
key := pbkdf2.Key([]byte("password"), []byte("salt"), 1000, 8, sha256.New)
fmt.Println(hex.EncodeToString(key))
// Derive 32 bytes then truncate to 16 characters: truncation happens after derivation
full := pbkdf2.Key([]byte("password"), []byte("salt"), 1000, 32, sha256.New)
fmt.Println(hex.EncodeToString(full)[:16])
}
632c2812e46d4604 632c2812e46d4604
Java v27.0.1
import java.util.HexFormat;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class Main {
public static void main(String[] args) throws Exception {
// SecretKeyFactory + PBEKeySpec: keyLength counts in bits (64 bits = 8 bytes)
PBEKeySpec spec = new PBEKeySpec("password".toCharArray(), "salt".getBytes(), 1000, 64);
byte[] key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
System.out.println(HexFormat.of().formatHex(key));
// Derive 256 bits (32 bytes) then truncate to 16 characters: truncation happens after derivation
spec = new PBEKeySpec("password".toCharArray(), "salt".getBytes(), 1000, 256);
byte[] full = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
System.out.println(HexFormat.of().formatHex(full).substring(0, 16));
}
}
632c2812e46d4604 632c2812e46d4604
JavaScript v26.13.1
// crypto.pbkdf2Sync: built into the standard library, keylen counts in bytes; the sync version blocks the main thread — use the async one in production
const crypto = require("node:crypto");
console.log(crypto.pbkdf2Sync("password", "salt", 1000, 8, "sha256").toString("hex"));
console.log(crypto.pbkdf2Sync("password", "salt", 1000, 32, "sha256").toString("hex").slice(0, 16));
632c2812e46d4604 632c2812e46d4604
PHP v8.6.0
// hash_pbkdf2: algo/password/salt/iterations/length (hex character count)
echo hash_pbkdf2("sha256", "password", "salt", 1000, 16), "\n";
// With raw_output=true the length unit becomes bytes
echo bin2hex(hash_pbkdf2("sha256", "password", "salt", 1000, 8, true)), "\n";
// Length truncation happens after derivation: a short output saves none of the iteration cost
echo substr(hash_pbkdf2("sha256", "password", "salt", 1000, 64), 0, 16);
632c2812e46d4604 632c2812e46d4604 632c2812e46d4604
Python v3.15.2
import hashlib
# hashlib.pbkdf2_hmac: built into the standard library, dklen counts in bytes
print(hashlib.pbkdf2_hmac("sha256", b"password", b"salt", 1000, dklen=8).hex())
print(hashlib.pbkdf2_hmac("sha256", b"password", b"salt", 1000, dklen=8).hex()[:16])
print(hashlib.pbkdf2_hmac("sha256", b"password", b"salt", 1000).hex()[:16])
632c2812e46d4604 632c2812e46d4604 632c2812e46d4604
Rust v1.99.1
// PBKDF2-HMAC-SHA256 (RFC 2898): no KDF in the standard library — hand-roll the HMAC on the sha2 crate, then iterate
use sha2::{Digest, Sha256};
// HMAC (RFC 2104): 64-byte block, two hash passes with ipad/opad
fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; 32] {
let mut k = [0u8; 64];
if key.len() > 64 {
k[..32].copy_from_slice(&Sha256::digest(key));
} else {
k[..key.len()].copy_from_slice(key);
}
let mut ipad = [0x36u8; 64];
let mut opad = [0x5cu8; 64];
for i in 0..64 {
ipad[i] ^= k[i];
opad[i] ^= k[i];
}
let mut inner = Sha256::new();
inner.update(ipad);
inner.update(msg);
let ih = inner.finalize();
let mut outer = Sha256::new();
outer.update(opad);
outer.update(ih);
outer.finalize().into()
}
// PBKDF2: U1 = PRF(P, S || INT_BE(i)), XOR-accumulated round by round; single-block scenario (≤32 bytes) demo
fn pbkdf2(pass: &[u8], salt: &[u8], iter: u32) -> [u8; 32] {
let mut msg = salt.to_vec();
msg.extend_from_slice(&1u32.to_be_bytes());
let mut u = hmac_sha256(pass, &msg);
let mut acc = u;
for _ in 1..iter {
u = hmac_sha256(pass, &u);
for j in 0..32 {
acc[j] ^= u[j];
}
}
acc
}
fn main() {
let hex: String = pbkdf2(b"password", b"salt", 1000)[..8]
.iter()
.map(|b| format!("{:02x}", b))
.collect();
println!("{}", hex);
}
632c2812e46d4604
TypeScript v26.13.1
import { pbkdf2Sync } from "node:crypto";
// keylen counts in bytes; the sync version blocks the event loop — use the await version in production
const key: Buffer = pbkdf2Sync("password", "salt", 1000, 8, "sha256");
console.log(key.toString("hex"));
console.log(pbkdf2Sync("password", "salt", 1000, 32, "sha256").toString("hex").slice(0, 16));
632c2812e46d4604 632c2812e46d4604
Language differences
C: no standard KDF — OpenSSL PKCS5_PBKDF2_HMAC or libsodium crypto_pwhash; the example hand-writes HMAC+PBKDF2 (RFC 2898) over the bundled vendor sha256.
C++: same hand-rolled approach as C; real work uses OpenSSL PKCS5_PBKDF2_HMAC or libsodium.
C#: Rfc2898DeriveBytes(password, salt, iterations, HashAlgorithmName) is built in; the instance is stream-like — successive GetBytes calls return the next segment, so Reset or a fresh instance to derive anew.
Go: lives in golang.org/x/crypto/pbkdf2 (extension module, not stdlib); Key(password, salt, iterations, keyLen, hash) in one call.
Java: SecretKeyFactory("PBKDF2WithHmacSHA256") plus PBEKeySpec — keyLength is in bits, don't pass bytes.
JavaScript: Node crypto.pbkdf2Sync (or the async pbkdf2); in browsers use WebCrypto deriveBits({name:"PBKDF2",...}).
PHP: hash_pbkdf2 is one call; $length counts hex characters by default (bytes when raw_output=true); for password storage prefer password_hash (auto salt and algorithm management).
Python: hashlib.pbkdf2_hmac(algo, password, salt, iterations, dklen) straight from the standard library; dklen is bytes, defaulting to the full digest.
Rust: no KDF in the standard library — the RustCrypto pbkdf2 crate (with hmac/sha2) is the idiom; the example hand-writes HMAC over sha2 to show the protocol layer.
TypeScript: same as JavaScript — Node crypto or WebCrypto.