Sample code for 30+ languages & platforms
Unicode C Requires Chilkat v11.6.0+

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 Unicode C Downloads

Unicode C
#include <C_CkCrypt2W.h>
#include <C_CkJsonObjectW.h>

void ChilkatSample(void)
    {
    HCkCrypt2W crypt;
    const wchar_t *password;
    HCkJsonObjectW json;
    const wchar_t *phcHash;

    crypt = CkCrypt2W_Create();

    //  The password should come from a secure source rather than being hard-coded.
    password = L"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 = CkJsonObjectW_Create();
    CkJsonObjectW_UpdateString(json,L"variant",L"argon2id");
    CkJsonObjectW_UpdateInt(json,L"memoryCostKb",131072);
    CkJsonObjectW_UpdateInt(json,L"iterations",4);
    CkJsonObjectW_UpdateInt(json,L"parallelism",2);
    CkJsonObjectW_UpdateInt(json,L"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.
    CkJsonObjectW_UpdateString(json,L"secret",L"application-wide-pepper");
    CkJsonObjectW_UpdateString(json,L"secretEncoding",L"utf-8");

    phcHash = CkCrypt2W_argon2HashPassword(crypt,password,CkJsonObjectW_emit(json));
    if (CkCrypt2W_getLastMethodSuccess(crypt) == FALSE) {
        wprintf(L"%s\n",CkCrypt2W_lastErrorText(crypt));
        CkCrypt2W_Dispose(crypt);
        CkJsonObjectW_Dispose(json);
        return;
    }

    wprintf(L"%s\n",phcHash);


    CkCrypt2W_Dispose(crypt);
    CkJsonObjectW_Dispose(json);

    }