Argon2id Password-Derived Keys

sodium_crypto_pwhash(length, password, salt, opslimit, memlimit, algo)

Derive a key from a password (Argon2id, memory-hard): with a fixed salt and parameters the derived key is deterministic and interoperable. A triangle with PBKDF2 (hash_pbkdf2) and bcrypt (password_hash) — memory hardness is the modern bar.

C C23

C23
#include <stdio.h>
#include <string.h>
#include "sha256.h" /* vendored SHA-256 stands in for the Argon2id internal hash */

/* sodium_crypto_pwhash teaching stand-in: the real thing is Argon2id
   (RFC 9106, memory-hard, needs Blake2b). Here: fixed wire facts + a
   plain hash-chain KDF so the data flow is visible. NOT secure. */

#define SALTBYTES 16

int main(void) {
    printf("alg: argon2id13 (id %d)\n", 2);
    printf("salt: 16 bytes, opslimit: 2, memlimit: 67108864 bytes\n");
    const char *password = "correct horse battery staple";
    BYTE salt[SALTBYTES];
    for (int i = 0; i < SALTBYTES; i++) salt[i] = (BYTE)i;
    /* hash chain: H(H(...H(password||salt))) x 2 — the shape of a KDF, not Argon2 */
    SHA256_CTX ctx;
    BYTE state[SHA256_BLOCK_SIZE];
    sha256_init(&ctx);
    sha256_update(&ctx, (const BYTE *)password, strlen(password));
    sha256_update(&ctx, salt, SALTBYTES);
    sha256_final(&ctx, state);
    for (int round = 0; round < 2; round++) {
        sha256_init(&ctx);
        sha256_update(&ctx, state, SHA256_BLOCK_SIZE);
        sha256_final(&ctx, state);
    }
    printf("kdf chain: ");
    for (int i = 0; i < 16; i++) printf("%02x", state[i]);
    printf("...\n");
    BYTE state2[SHA256_BLOCK_SIZE];
    sha256_init(&ctx);
    sha256_update(&ctx, (const BYTE *)password, strlen(password));
    sha256_update(&ctx, salt, SALTBYTES);
    sha256_final(&ctx, state2);
    for (int round = 0; round < 2; round++) {
        sha256_init(&ctx);
        sha256_update(&ctx, state2, SHA256_BLOCK_SIZE);
        sha256_final(&ctx, state2);
    }
    printf("deterministic: %s\n", memcmp(state, state2, SHA256_BLOCK_SIZE) == 0 ? "true" : "false");
    return 0;
}
Output
alg: argon2id13 (id 2)
salt: 16 bytes, opslimit: 2, memlimit: 67108864 bytes
kdf chain: 56241492e725842b1a28cfc096b33115...
deterministic: true

C++ C++26

C++26
#include <cstdio>
#include <cstring>
#include <string>
#include "sha256.h" // vendored SHA-256 stands in for the Argon2id internal hash

// sodium_crypto_pwhash teaching stand-in: real = Argon2id (RFC 9106,
// memory-hard, needs Blake2b). Here: fixed wire facts + a hash-chain KDF
// so the data flow is visible. NOT secure.

int main() {
    std::printf("alg: argon2id13 (id %d)\n", 2);
    std::printf("salt: 16 bytes, opslimit: 2, memlimit: 67108864 bytes\n");
    std::string password = "correct horse battery staple";
    unsigned char salt[16];
    for (int i = 0; i < 16; i++) salt[i] = (unsigned char)i;
    auto chain = [&](unsigned char out[SHA256_BLOCK_SIZE]) {
        SHA256_CTX ctx;
        sha256_init(&ctx);
        sha256_update(&ctx, (const BYTE *)password.data(), password.size());
        sha256_update(&ctx, salt, 16);
        sha256_final(&ctx, out);
        for (int round = 0; round < 2; round++) {
            sha256_init(&ctx);
            sha256_update(&ctx, out, SHA256_BLOCK_SIZE);
            sha256_final(&ctx, out);
        }
    };
    BYTE state[SHA256_BLOCK_SIZE], state2[SHA256_BLOCK_SIZE];
    chain(state);
    std::printf("kdf chain: ");
    for (int i = 0; i < 16; i++) std::printf("%02x", state[i]);
    std::printf("...\n");
    chain(state2); // same password + same salt -> same key
    std::printf("deterministic: %s\n", std::memcmp(state, state2, 32) == 0 ? "true" : "false");
    return 0;
}
Output
alg: argon2id13 (id 2)
salt: 16 bytes, opslimit: 2, memlimit: 67108864 bytes
kdf chain: 56241492e725842b1a28cfc096b33115...
deterministic: true

C# v11.0.100

v11.0.100
using System.Security.Cryptography;

// Rfc2898DeriveBytes = PBKDF2 (CPU-hard, NOT memory-hard); Argon2id needs a
// NuGet package (Konscious.Security.Cryptography.Argon2) — notes detail
byte[] salt = new byte[16];
for (int i = 0; i < 16; i++) salt[i] = (byte)i;
using var kdf = new Rfc2898DeriveBytes("correct horse battery staple", salt, 100_000, HashAlgorithmName.SHA256);
Console.WriteLine("pbkdf2: " + Convert.ToHexString(kdf.GetBytes(32)).ToLower());
Console.WriteLine("argon2id: use Konscious (notes) - BCL ships PBKDF2 only");
Output
pbkdf2: 49d49c25f597846209f0d92e7770ab64e1c75e94b4ce6c509265ee67175d2a1e
argon2id: use Konscious (notes) - BCL ships PBKDF2 only

Go v1.27.4

v1.27.4
package main

import (
	"encoding/hex"
	"fmt"

	"golang.org/x/crypto/argon2"
)

func main() {
	// Argon2id (RFC 9106) — byte-for-byte identical to PHP sodium_crypto_pwhash
	salt := []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}
	key := argon2.IDKey([]byte("correct horse battery staple"), salt, 2, 64*1024, 1, 32)
	fmt.Println("argon2id:", hex.EncodeToString(key))
	fmt.Println("interop: matches libsodium with ops=2, mem=64MiB, lanes=1")
}
Output
argon2id: c05ce4c4dd7e0e45ee6011cc59d068ade47df1b01fc0cf9cd4678bdf68a5b7b0
interop: matches libsodium with ops=2, mem=64MiB, lanes=1

Java v27.0.1

v27.0.1
import java.security.spec.KeySpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.util.HexFormat;

public class Main {
    public static void main(String[] args) throws Exception {
        // PBKDF2WithHmacSHA256 is the JDK's built-in KDF (CPU-hard, NOT memory-hard);
        // Argon2id needs BouncyCastle (org.bouncycastle.crypto.params.Argon2Parameters)
        byte[] salt = new byte[16];
        for (int i = 0; i < 16; i++) salt[i] = (byte) i;
        SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec("correct horse battery staple".toCharArray(), salt, 100_000, 256);
        byte[] key = f.generateSecret(spec).getEncoded();
        System.out.println("pbkdf2: " + HexFormat.of().formatHex(key));
        System.out.println("argon2id: use BouncyCastle (notes) - JDK ships PBKDF2 only");
    }
}
Output
pbkdf2: 49d49c25f597846209f0d92e7770ab64e1c75e94b4ce6c509265ee67175d2a1e
argon2id: use BouncyCastle (notes) - JDK ships PBKDF2 only

JavaScript v26.13.1

v26.13.1
// Node's KDF is scrypt (memory-hard, RFC 7914) — same family as Argon2id but
// a different algorithm; no stdlib Argon2 (libsodium.js in the notes)
const crypto = require('node:crypto');
const salt = Buffer.alloc(16);
for (let i = 0; i < 16; i++) salt[i] = i;
const k = crypto.scryptSync('correct horse battery staple', salt, 32, {
  N: 16384, r: 8, p: 1, maxmem: 64 * 1024 * 1024,
});
console.log('scrypt:', k.toString('hex'));
const k2 = crypto.scryptSync('correct horse battery staple', salt, 32, {
  N: 16384, r: 8, p: 1, maxmem: 64 * 1024 * 1024,
});
console.log('deterministic:', k.equals(k2));
Output
scrypt: d7590aca2c9801cf06eeba772a69dc31ce3862591d96522ac4e6bba6ad1f31a5
deterministic: true

PHP v8.6.0

v8.6.0
// sodium_crypto_pwhash: Argon2id (RFC 9106). Fixed salt + parameters ->
// a deterministic derived key (it interoperates byte-for-byte with Go's
// golang.org/x/crypto/argon2 and RustCrypto argon2, see the notes)
$salt = hex2bin("000102030405060708090a0b0c0d0e0f"); // 16 bytes, keep it to verify later
$key = sodium_crypto_pwhash(
    32,
    "correct horse battery staple",
    $salt,
    SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
    SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE,
    SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13
);
echo "argon2id: ", bin2hex($key), PHP_EOL;
echo "saltbytes: ", SODIUM_CRYPTO_PWHASH_SALTBYTES, " ops: ", SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
    " mem: ", SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE, PHP_EOL;
// for password storage use sodium_crypto_pwhash_str (salt+params embedded in the string)
echo "storage form uses: sodium_crypto_pwhash_str (params embedded)", PHP_EOL;
Output
argon2id: c05ce4c4dd7e0e45ee6011cc59d068ade47df1b01fc0cf9cd4678bdf68a5b7b0
saltbytes: 16 ops: 2 mem: 67108864
storage form uses: sodium_crypto_pwhash_str (params embedded)

Python v3.15.2

v3.15.2
import hashlib

# hashlib.scrypt is the standard-library KDF (memory-hard like Argon2id but a
# different algorithm, RFC 7914); Python has no stdlib Argon2, notes name libs
salt = bytes(range(16))
k = hashlib.scrypt(b"correct horse battery staple", salt=salt, n=16384, r=8, p=1, dklen=32)
print("scrypt:", k.hex())
# determinism: same password + same salt -> same key
k2 = hashlib.scrypt(b"correct horse battery staple", salt=salt, n=16384, r=8, p=1, dklen=32)
print("deterministic:", k == k2)
print("params: N=16384 r=8 p=1 (memory-hard work factors)")
Output
scrypt: d7590aca2c9801cf06eeba772a69dc31ce3862591d96522ac4e6bba6ad1f31a5
deterministic: True
params: N=16384 r=8 p=1 (memory-hard work factors)

Rust v1.99.1

v1.99.1
// argon2 crate (RustCrypto): byte-for-byte identical to libsodium
use argon2::{Algorithm, Argon2, Params, Version};

fn main() {
    let salt = [0x00u8, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f];
    // Argon2id v1.3, m = 64 MiB, t = 2, p = 1 — the Interactive preset
    let a2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, Params::new(65536, 2, 1, None).unwrap());
    let mut out = [0u8; 32];
    a2.hash_password_into(b"correct horse battery staple", &salt, &mut out).unwrap();
    let hexs: String = out.iter().map(|b| format!("{:02x}", b)).collect();
    println!("argon2id: {}", hexs);
    println!("interop: matches libsodium and golang.org/x/crypto/argon2");
}
Output
argon2id: c05ce4c4dd7e0e45ee6011cc59d068ade47df1b01fc0cf9cd4678bdf68a5b7b0
interop: matches libsodium and golang.org/x/crypto/argon2

TypeScript v26.13.1

v26.13.1
// Typed same as the JS block: Node's scrypt KDF.
import { scryptSync, createHash } from 'node:crypto';
import { Buffer } from 'node:buffer';

const salt: Buffer = Buffer.alloc(16);
for (let i = 0; i < 16; i++) salt[i] = i;
const opts = { N: 16384, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
const k: Buffer = scryptSync('correct horse battery staple', salt, 32, opts);
console.log('scrypt:', k.toString('hex'));
const k2: Buffer = scryptSync('correct horse battery staple', salt, 32, opts);
console.log('deterministic:', k.equals(k2));
console.log('params: N=16384 r=8 p=1');
Output
scrypt: d7590aca2c9801cf06eeba772a69dc31ce3862591d96522ac4e6bba6ad1f31a5
deterministic: true
params: N=16384 r=8 p=1

Language differences

A triangle: Argon2id (this entry, memory-hard) vs PBKDF2 (hash_pbkdf2 entry, CPU-hard) vs bcrypt (password_hash entry, salted with a built-in cost factor) — OWASP currently prefers Argon2id; password storage uses the *_str family (salt+params embedded), key derivation uses the raw functions.

PHP: sodium_crypto_pwhash is the low-level API (password storage should use sodium_crypto_pwhash_str / password_hash); SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE=2, MEMLIMIT_INTERACTIVE=64MiB, SALTBYTES=16; pin SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13 explicitly (the default may drift across libsodium versions).

C/C++: no KDF in the standard library — the example uses a vendored SHA-256 hash chain to show the password+salt->key data flow (not a secure construction); production links libsodium directly (available on this machine).

C#: the BCL ships only PBKDF2 (Rfc2898DeriveBytes); for Argon2id use Konscious.Security.Cryptography.Argon2 (NuGet) or the libsodium binding NSec.

Go: golang.org/x/crypto/argon2 interoperates byte-for-byte with libsodium (both RFC 9106) — verified here: with ops=2, mem=64MiB, lanes=1 the derived key matches PHP.

Java: the JDK ships PBKDF2 only; Argon2id via BouncyCastle (Argon2Parameters).

JavaScript: Node ships scrypt (crypto.scryptSync); Argon2 via libsodium.js or the argon2 npm package (C binding).

Python: standard-library scrypt (hashlib.scrypt, also memory-hard); Argon2 via argon2-cffi (pip).

Rust: the argon2 crate (RustCrypto) matches libsodium byte for byte (verified here: PHP/Go/Rust all derive the same key).

TypeScript: same as JavaScript.