Contents · Forum Home · StreamSec Tools 4.1.5.364 documentation

Store a password safely

A stored password should be one that a thief of the database cannot read back and cannot cheaply guess against. Argon2id (RFC 9106) does both: each password gets its own random salt, and each guess costs the attacker the same memory and time it costs you once per sign-in.

The units

uses
  System.SysUtils,
  System.NetEncoding,      // TBase64Encoding
  stSecUtils,              // EqualMemConstantTime, ProtectClear
  stRandom, stDrbgAesCtr,  // the salt
  stAESNI, stAESCT,        // the AES the random generator runs on
  StreamSec.DSI.Argon2;    // Argon2id (RFC 9106)

The salt comes from the random generator, which runs on AES: Generate random bytes and keys says which AES units to link and why.

Hash a password for storing

const
  { RFC 9106 section 4, the second recommended option: 64 MiB, 3 passes,
    4 lanes. Raise the memory if the server can afford it; the stored string
    records the values, so old hashes keep verifying after a change. }
  cMemoryKiB = 65536;
  cPasses = 3;
  cLanes = 4;
  cSaltLen = 16;
  cHashLen = 32;

function B64(const aBytes: TBytes): string;
var
  lEnc: TBase64Encoding;
begin
  lEnc := TBase64Encoding.Create(0);   // no line breaks
  try
    Result := lEnc.EncodeBytesToString(aBytes).TrimRight(['=']);
  finally
    lEnc.Free;
  end;
end;

function UnB64(const aText: string): TBytes;
var
  lEnc: TBase64Encoding;
  lText: string;
begin
  lText := aText;
  while Length(lText) mod 4 <> 0 do
    lText := lText + '=';
  lEnc := TBase64Encoding.Create(0);
  try
    Result := lEnc.DecodeStringToBytes(lText);
  finally
    lEnc.Free;
  end;
end;

{ The PHC string format that other Argon2 implementations read and write:
  $argon2id$v=19$m=65536,t=3,p=4$<salt>$<hash> }
function HashPassword(const aPassword: string): string;
var
  lPassword, lSalt, lHash: TBytes;
begin
  { The password as typed - its UTF-8 octets, nothing trimmed or folded. }
  lPassword := TEncoding.UTF8.GetBytes(aPassword);
  try
    SetLength(lSalt, cSaltLen);
    GetRawRandom(True).RawRandom(lSalt);
    lHash := Argon2id(lPassword, lSalt, nil, nil, cLanes, cMemoryKiB, cPasses, cHashLen);
    Result := Format('$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s',
                     [cMemoryKiB, cPasses, cLanes, B64(lSalt), B64(lHash)]);
  finally
    ProtectClear(lPassword);
  end;
end;

The result is one string, in the format the other Argon2 implementations use, which records the parameters and the salt beside the hash - store it as it is. An Argon2id string made by another implementation in this format verifies here - libsodium's, for instance. The other way round depends on the other side: libsodium only computes one lane, so if a libsodium-based system has to verify the strings made here, set cLanes to 1.

Hash the password exactly as the user typed it. Trimming spaces, changing
case or normalising it first means two different passwords can sign in as
one, and a user who typed a trailing space can no longer get in.

Check a password at sign-in

function VerifyPassword(const aPassword, aStored: string): Boolean;
var
  lParts, lParams: TArray<string>;
  lPassword, lSalt, lExpected, lHash: TBytes;
  lMemory, lPasses, lLanes: Integer;
begin
  Result := False;
  { '', 'argon2id', 'v=19', 'm=..,t=..,p=..', salt, hash }
  lParts := aStored.Split(['$']);
  if (Length(lParts) <> 6) or (lParts[1] <> 'argon2id') or (lParts[2] <> 'v=19') then
    Exit;
  lParams := lParts[3].Split([',']);
  if (Length(lParams) <> 3) or
     not TryStrToInt(lParams[0].Substring(2), lMemory) or
     not TryStrToInt(lParams[1].Substring(2), lPasses) or
     not TryStrToInt(lParams[2].Substring(2), lLanes) then
    Exit;
  { The cost comes from the stored string; bound it, so a damaged or planted
    entry cannot make one sign-in claim gigabytes or minutes. }
  if (lMemory < 8 * lLanes) or (lMemory > 1048576) or (lPasses < 1) or
     (lPasses > 16) or (lLanes < 1) or (lLanes > 16) then
    Exit;
  lSalt := UnB64(lParts[4]);
  lExpected := UnB64(lParts[5]);
  if Length(lExpected) = 0 then
    Exit;
  lPassword := TEncoding.UTF8.GetBytes(aPassword);
  try
    lHash := Argon2id(lPassword, lSalt, nil, nil, lLanes, lMemory, lPasses, Length(lExpected));
  finally
    ProtectClear(lPassword);
  end;
  Result := EqualMemConstantTime(lHash[0], lExpected[0], Length(lExpected));
end;

The comparison is in constant time (EqualMemConstantTime), so the time it takes says nothing about how close a guess was.

Choosing the cost

The values above are RFC 9106's second recommendation: 64 MiB of memory, 3 passes, 4 lanes - around a tenth of a second on a current server. More memory is the better protection; raise it as far as the server can carry for the number of sign-ins it handles at once. Since every stored string records its own parameters, raising them later only affects new hashes; an application can rehash at the next successful sign-in.

For deriving an encryption key from a password rather than storing a verifier, call Argon2id the same way and use the output as the key - see Encrypt data with AES-GCM.

Reference

StreamSec.DSI.Argon2

Related tasks