Contents · Forum Home · StreamSec Tools 4.1.5.364 documentation

Generate random bytes and keys

Keys, salts, nonces and session identifiers have to be unpredictable, which System.Random is not. The library generates them with an SP 800-90A DRBG, seeded and reseeded from its own SP 800-90B entropy source.

The units

uses
  System.SysUtils,
  stSecUtils,     // iRawRandomEx
  stRandom,       // GetRawRandom
  stDrbgAesCtr,   // installs the library's SP 800-90A DRBG as the generator
  stAESNI,        // AES in hardware, on CPUs that have it
  stAESCT;        // constant-time software AES on every other CPU

stDrbgAesCtr installs the generator when it is linked. The TLS, SSH and mail components link it themselves, so a program that uses one of them already has a generator; a program that only does cryptography of its own names the unit.

Which AES unit

The generator is AES-256 in counter mode (the CTR_DRBG of SP 800-90A), and it finds its AES implementation at run time among the units linked into the program. Name both of these, and each computer uses the right one:

Neither covers for the other, so link both. Do not name stAES instead: its table lookups depend on the key and the data, so their timing can give both away; with the two units above linked it is never used.

With no AES unit linked, the generator cannot start, and GetRawRandom raises eRandom ("Unable to create instance"). The TLS, SSH and mail components link both units themselves.

A key

function NewKey(aBytes: Integer): TBytes;
begin
  { Key material comes from the PRIMARY generator: the shared DRBG seeded
    and reseeded from the entropy source. }
  SetLength(Result, aBytes);
  GetRawRandom(False).RawRandom(Result);
end;

NewKey(32) is a 256-bit key, for example for Encrypt data with AES-GCM or an HMAC (Compute a SHA-256 hash and an HMAC).

Many values: a secondary generator

threadvar
  gSessionRandom: iRawRandomEx;

function NewSessionId: string;
var
  lId: TBytes;
  I: Integer;
begin
  { Values that must be unpredictable but are not key material - session
    ids, nonces - come from a SECONDARY generator: an independent DRBG
    seeded from the primary. Take one per thread (or per connection) and
    keep it; a new one per call costs a reseed from the primary. }
  if gSessionRandom = nil then
    gSessionRandom := GetRawRandom(True);
  SetLength(lId, 16);
  gSessionRandom.RawRandom(lId);
  Result := '';
  for I := 0 to High(lId) do
    Result := Result + LowerCase(IntToHex(lId[I], 2));
end;

Which generator for what

The DRBG and entropy source notes describe the generators, the entropy source and its health tests, and when a platform or hardware generator is the better choice.

Reference

stRandom · stDrbgAesCtr

Related tasks