YOUSEFUL / DELPHI / COMPONENTS
TAtlasRandom
Cryptographically secure random bytes, unbiased integers and URL-safe tokens from the operating system.
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
| Member | Kind | What it does |
|---|---|---|
Bytes | method | Returns Count random bytes. |
Below | method | Returns a uniformly distributed number from 0 to Limit - 1. |
Token | method | Returns 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.
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.
Roll := TAtlasRandom.Below(6) + 1; // 1 to 6Token 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.
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.
uses System.SysUtils, Atlas.Crypto;
procedure MakeCodes;
begin
WriteLn(Format('%.6d', [TAtlasRandom.Below(1000000)]));
WriteLn(TAtlasRandom.Token);
end;