Rust Requires Chilkat v11.6.0+
Rust
Argon2 Key Derivation with a Secret (Pepper), AD, and Encodings
Demonstrates the optional Argon2 options for Crypt2.Argon2DeriveKey: secret (a pepper), ad (associated data), the encoding member and its per-member overrides saltEncoding/secretEncoding/adEncoding, passwordCharset, and maxMemoryKb.
Background. A pepper is a secret value held by the application and not stored with the hash, so a stolen hash database cannot be attacked without it. The encoding members control how the salt, secret, and ad text are interpreted as bytes (
base64 by default; utf-8 uses the characters themselves). maxMemoryKb is a guard against an unreasonable memory cost.Chilkat Rust Downloads
let crypt = chilkat::Crypt2::new();
// The password should come from a secure source rather than being hard-coded.
let password = "correct horse battery staple".to_string();
// Build the Argon2 options JSON, this time using the optional secret, ad, and encoding members.
// secret the RFC 9106 secret value K, often called a "pepper": a key held by the
// application and NOT stored with the hash, so a stolen hash database cannot be
// attacked without it.
// ad optional associated data X: additional non-secret data bound into the derivation.
// encoding how salt, secret, and ad are encoded (default base64). Per-member overrides are
// saltEncoding, secretEncoding, and adEncoding.
// passwordCharset the charset the password is converted to before use (default utf-8).
// maxMemoryKb a guard (not an Argon2 parameter) refusing to allocate more than this many KB;
// default 2097152 (2 GB).
let json = chilkat::JsonObject::new();
// The salt is provided here as hex, overriding the default base64 for just this member.
let _ = json.update_string("salt", "0102030405060708090a0b0c0d0e0f10");
let _ = json.update_string("saltEncoding", "hex");
// The pepper is supplied as UTF-8 text (its own characters are the bytes).
let _ = json.update_string("secret", "application-wide-pepper");
let _ = json.update_string("secretEncoding", "utf-8");
// Associated data, supplied as UTF-8 text.
let _ = json.update_string("ad", "user-id-42");
let _ = json.update_string("adEncoding", "utf-8");
let _ = json.update_string("passwordCharset", "utf-8");
let _ = json.update_int("maxMemoryKb", 1048576);
let _ = json.update_int("keyLen", 32);
let bd_key = chilkat::BinData::new();
if crypt.argon2_derive_key(&password, &json.emit().unwrap_or_default(), &bd_key).is_err() {
println!("{}", crypt.last_error_text());
return;
}
let Ok(key_hex) = bd_key.get_encoded("hex") else {
println!("{}", bd_key.last_error_text());
return;
};
println!("Derived key: {}", key_hex);