YOUSEFUL / DELPHI / COMPONENTS

TAtlasRandom

Cryptographically secure random bytes, unbiased integers and URL-safe tokens from the operating system.

Class Unit Atlas.Crypto · Inherits TObject · Product Atlas Crypto

Description

Class functions over the system-preferred CNG random generator (BCryptGenRandom). Unlike the RTL's Random, the output is unpredictable, needs no seeding and is suitable for keys, salts, nonces, session tokens and one-time codes. Safe to call from any thread.

Members

MemberKindWhat it does
BytesmethodReturns Count random bytes.
BelowmethodReturns a uniformly distributed number from 0 to Limit - 1.
TokenmethodReturns ByteCount random bytes as URL-safe base64 without padding, for session tokens, reset links and API keys.

Methods

Bytes method

class function Bytes(Count: Integer): TBytes; static;

Returns Count random bytes. Count must be 0 to 64 MB (67,108,864); anything else raises EAtlasCryptoError.

pascal
Salt := TAtlasRandom.Bytes(16);

Below method

class function Below(Limit: Cardinal): Cardinal; static;

Returns a uniformly distributed number from 0 to Limit - 1. Uses rejection sampling rather than mod, so small results are not favoured. Limit must be at least 1.

pascal
Roll := TAtlasRandom.Below(6) + 1;  // 1 to 6

Token method

class function Token(ByteCount: Integer = 32): string; static;

Returns ByteCount random bytes as URL-safe base64 without padding, for session tokens, reset links and API keys. The default 32 bytes give 43 characters. Fewer than 16 bytes raises EAtlasCryptoError, because such a token could be guessed.

pascal
Token := TAtlasRandom.Token;

Examples

Make a one-time code and a reset token

Prints a six-digit code such as 084213 and a 43-character token.

pascal
uses System.SysUtils, Atlas.Crypto;

procedure MakeCodes;
begin
  WriteLn(Format('%.6d', [TAtlasRandom.Below(1000000)]));
  WriteLn(TAtlasRandom.Token);
end;

TAtlasBytes · TAtlasSecretBox

Also in Atlas Crypto

TAtlasHashCalculator · TAtlasFileProtector