Tcl Requires Chilkat v11.6.0+
Tcl
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 Tcl Downloads
load ./chilkat.dll
set success 0
set crypt [new_CkCrypt2]
# The password should come from a secure source rather than being hard-coded.
set password "correct horse battery staple"
# 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).
set json [new_CkJsonObject]
# The salt is provided here as hex, overriding the default base64 for just this member.
CkJsonObject_UpdateString $json "salt" "0102030405060708090a0b0c0d0e0f10"
CkJsonObject_UpdateString $json "saltEncoding" "hex"
# The pepper is supplied as UTF-8 text (its own characters are the bytes).
CkJsonObject_UpdateString $json "secret" "application-wide-pepper"
CkJsonObject_UpdateString $json "secretEncoding" "utf-8"
# Associated data, supplied as UTF-8 text.
CkJsonObject_UpdateString $json "ad" "user-id-42"
CkJsonObject_UpdateString $json "adEncoding" "utf-8"
CkJsonObject_UpdateString $json "passwordCharset" "utf-8"
CkJsonObject_UpdateInt $json "maxMemoryKb" 1048576
CkJsonObject_UpdateInt $json "keyLen" 32
set bdKey [new_CkBinData]
set success [CkCrypt2_Argon2DeriveKey $crypt $password [CkJsonObject_emit $json] $bdKey]
if {$success == 0} then {
puts [CkCrypt2_lastErrorText $crypt]
delete_CkCrypt2 $crypt
delete_CkJsonObject $json
delete_CkBinData $bdKey
exit
}
set keyHex [CkBinData_getEncoded $bdKey "hex"]
if {[CkBinData_get_LastMethodSuccess $bdKey] == 0} then {
puts [CkBinData_lastErrorText $bdKey]
delete_CkCrypt2 $crypt
delete_CkJsonObject $json
delete_CkBinData $bdKey
exit
}
puts "Derived key: $keyHex"
delete_CkCrypt2 $crypt
delete_CkJsonObject $json
delete_CkBinData $bdKey