PureBasic Requires Chilkat v11.6.0+
PureBasic
Hash a Password with Argon2 (Tuned Options)
Demonstrates Crypt2.Argon2HashPassword with explicit options: the cost parameters, saltLen (how many random salt bytes to generate when no salt is given), and an optional secret (pepper).
Background. For hashing, the salt is optional — when omitted, a random salt of
saltLen bytes (default 16) is generated, which is the normal case. A secret or ad is not stored in the PHC string; the same values must be supplied to Argon2VerifyPassword for the password to verify.Chilkat PureBasic Downloads
IncludeFile "CkCrypt2.pb"
IncludeFile "CkJsonObject.pb"
Procedure ChilkatExample()
crypt.i = CkCrypt2::ckCreate()
If crypt.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
; The password should come from a secure source rather than being hard-coded.
password.s = "correct horse battery staple"
; The Argon2 options are the same members as Argon2DeriveKey, except the salt is optional for
; hashing. When no "salt" is given, a random salt is generated; "saltLen" (default 16, range 8..1024)
; sets how many random bytes to use.
json.i = CkJsonObject::ckCreate()
If json.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkJsonObject::ckUpdateString(json,"variant","argon2id")
CkJsonObject::ckUpdateInt(json,"memoryCostKb",131072)
CkJsonObject::ckUpdateInt(json,"iterations",4)
CkJsonObject::ckUpdateInt(json,"parallelism",2)
CkJsonObject::ckUpdateInt(json,"saltLen",16)
; A secret (pepper) and/or ad may be used, but neither is stored in the returned PHC string. The
; same values must be supplied to Argon2VerifyPassword for the password to verify.
CkJsonObject::ckUpdateString(json,"secret","application-wide-pepper")
CkJsonObject::ckUpdateString(json,"secretEncoding","utf-8")
phcHash.s = CkCrypt2::ckArgon2HashPassword(crypt,password,CkJsonObject::ckEmit(json))
If CkCrypt2::ckLastMethodSuccess(crypt) = 0
Debug CkCrypt2::ckLastErrorText(crypt)
CkCrypt2::ckDispose(crypt)
CkJsonObject::ckDispose(json)
ProcedureReturn
EndIf
Debug phcHash
CkCrypt2::ckDispose(crypt)
CkJsonObject::ckDispose(json)
ProcedureReturn
EndProcedure