Argon2id 密码派生
sodium_crypto_pwhash(length, password, salt, opslimit, memlimit, algo)
从口令派生密钥(Argon2id,内存硬):固定 salt + 参数下派生值确定,可互操作对齐。与 PBKDF2(hash_pbkdf2)、bcrypt(password_hash)三角对照——内存硬是现代密码哈希的门槛。
C C23
#include <stdio.h>
#include <string.h>
#include "sha256.h" /* vendor 的 SHA-256 顶替 Argon2id 的内部哈希 */
/* sodium_crypto_pwhash 教学替身:真实现是 Argon2id(RFC 9106,内存硬,
需要 Blake2b)。这里打印固定 wire 事实 + 普通 hash 链 KDF 展示数据流。
不安全。 */
#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 链:H(H(...H(password||salt))) x 2——KDF 的形状,不是 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;
}
alg: argon2id13 (id 2) salt: 16 bytes, opslimit: 2, memlimit: 67108864 bytes kdf chain: 56241492e725842b1a28cfc096b33115... deterministic: true
C++ C++26
#include <cstdio>
#include <cstring>
#include <string>
#include "sha256.h" // vendor 的 SHA-256 顶替 Argon2id 的内部哈希
// sodium_crypto_pwhash 教学替身:真实现是 Argon2id(RFC 9106,内存硬,
// 需要 Blake2b)。这里打印固定 wire 事实 + hash 链 KDF 展示数据流。
// 不安全。
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); // 同口令 + 同 salt -> 同派生密钥
std::printf("deterministic: %s\n", std::memcmp(state, state2, 32) == 0 ? "true" : "false");
return 0;
}
alg: argon2id13 (id 2) salt: 16 bytes, opslimit: 2, memlimit: 67108864 bytes kdf chain: 56241492e725842b1a28cfc096b33115... deterministic: true
C# v11.0.100
using System.Security.Cryptography;
// Rfc2898DeriveBytes = PBKDF2(CPU 难、非内存难);Argon2id 需要 NuGet 包
//(Konscious.Security.Cryptography.Argon2)——notes 详述
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");
pbkdf2: 49d49c25f597846209f0d92e7770ab64e1c75e94b4ce6c509265ee67175d2a1e argon2id: use Konscious (notes) - BCL ships PBKDF2 only
Go v1.27.4
package main
import (
"encoding/hex"
"fmt"
"golang.org/x/crypto/argon2"
)
func main() {
// Argon2id(RFC 9106)——与 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")
}
argon2id: c05ce4c4dd7e0e45ee6011cc59d068ade47df1b01fc0cf9cd4678bdf68a5b7b0 interop: matches libsodium with ops=2, mem=64MiB, lanes=1
Java 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 是 JDK 内置 KDF(CPU 难、非内存难);
// Argon2id 需要 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");
}
}
pbkdf2: 49d49c25f597846209f0d92e7770ab64e1c75e94b4ce6c509265ee67175d2a1e argon2id: use BouncyCastle (notes) - JDK ships PBKDF2 only
JavaScript v26.13.1
// Node 的内置 KDF 是 scrypt(内存硬,RFC 7914)——与 Argon2id 同族但算法不同;
// 标准库无 Argon2(notes 指向 libsodium.js)
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));
scrypt: d7590aca2c9801cf06eeba772a69dc31ce3862591d96522ac4e6bba6ad1f31a5 deterministic: true
PHP v8.6.0
// sodium_crypto_pwhash:Argon2id(RFC 9106)。固定 salt + 参数下派生值确定
//(与 Go golang.org/x/crypto/argon2、RustCrypto argon2 逐字节互操作,见 notes)
$salt = hex2bin("000102030405060708090a0b0c0d0e0f"); // 16 字节,必须保存才能后续校验
$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;
// 存口令用 sodium_crypto_pwhash_str(salt+参数内嵌在字符串里)
echo "storage form uses: sodium_crypto_pwhash_str (params embedded)", PHP_EOL;
argon2id: c05ce4c4dd7e0e45ee6011cc59d068ade47df1b01fc0cf9cd4678bdf68a5b7b0 saltbytes: 16 ops: 2 mem: 67108864 storage form uses: sodium_crypto_pwhash_str (params embedded)
Python v3.15.2
import hashlib
# hashlib.scrypt 是标准库 KDF(与 Argon2id 同为内存硬但算法不同,RFC 7914);
# Python 标准库无 Argon2,notes 列出第三方库
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())
# 确定性:同口令 + 同 salt -> 同派生密钥
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)")
scrypt: d7590aca2c9801cf06eeba772a69dc31ce3862591d96522ac4e6bba6ad1f31a5 deterministic: True params: N=16384 r=8 p=1 (memory-hard work factors)
Rust v1.99.1
// argon2 crate(RustCrypto):与 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——即 Interactive 预设
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");
}
argon2id: c05ce4c4dd7e0e45ee6011cc59d068ade47df1b01fc0cf9cd4678bdf68a5b7b0 interop: matches libsodium and golang.org/x/crypto/argon2
TypeScript v26.13.1
// 与 JS 块同构带类型:Node 的 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');
scrypt: d7590aca2c9801cf06eeba772a69dc31ce3862591d96522ac4e6bba6ad1f31a5 deterministic: true params: N=16384 r=8 p=1
语言差异说明
三角对照:Argon2id(本条,内存硬)vs PBKDF2(hash_pbkdf2 条目,CPU 硬)vs bcrypt(password_hash 条目,加盐 + 内置成本因子)——OWASP 现行推荐 Argon2id 优先;口令存储用 *_str 系(salt+参数内嵌),密钥派生用 raw 函数。
PHP:sodium_crypto_pwhash 是低层接口(口令存储应使用 sodium_crypto_pwhash_str / password_hash);SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE=2、MEMLIMIT_INTERACTIVE=64MiB、SALTBYTES=16;alg 显式钉死 SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13(默认值可能随 libsodium 演进变化)。
C/C++:stdlib 无 KDF——示例用 vendor SHA-256 hash 链展示「口令 + salt -> 密钥」数据流(非安全实现);生产直接链 libsodium(本机即有)。
C#:BCL 只有 PBKDF2(Rfc2898DeriveBytes);Argon2id 用 Konscious.Security.Cryptography.Argon2(NuGet)或 libsodium 绑定 NSec。
Go:golang.org/x/crypto/argon2 与 libsodium 逐字节互操作(同 RFC 9106 实现)——本条已实测:ops=2、mem=64MiB、lanes=1 下与 PHP 派生值一致。
Java:JDK 只有 PBKDF2;Argon2id 用 BouncyCastle(Argon2Parameters)。
JavaScript:Node 内置 scrypt(crypto.scryptSync);Argon2 用 libsodium.js 或 argon2 npm 包(C 绑定)。
Python:标准库 scrypt(hashlib.scrypt,同为内存硬);Argon2 用 argon2-cffi(pip)。
Rust:argon2 crate(RustCrypto)与 libsodium 逐字节一致(本条已实测三方互证:PHP/Go/Rust 同一派生值)。
TypeScript:同 JavaScript。