Skip to content

Instantly share code, notes, and snippets.

@jimmckeeth
Last active August 15, 2023 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jimmckeeth/2c66e7c4fee55d56ad9928606f6cc197 to your computer and use it in GitHub Desktop.
Save jimmckeeth/2c66e7c4fee55d56ad9928606f6cc197 to your computer and use it in GitHub Desktop.
Delphi Cryptographically Secure Random Number Generator that works on all paltforms
// Tested on Windows, MacOS, Linux, and Android. From what I've read /dev/urandom works on iOS too.
unit MultiPlatformCryptoRando;
interface
uses System.Classes, System.SysUtils;
function CryptoRandoCardinal: Cardinal;
function CryptoRandoFloat: Single;
function CryptoRandoRange(max: Cardinal): Cardinal;
implementation
{$IFDEF MSWindows}
uses WinAPI.Security.Cryptography;
{$ENDIF}
function CryptoRandoRange(max: Cardinal): Cardinal;
begin
Result := CryptoRandoCardinal mod Max;
end;
function CryptoRandoFloat: Single;
begin
Result := CryptoRandoCardinal/4294967295;
end;
function CryptoRandoCardinal: Cardinal;
begin
{$IFDEF MSWindows}
var b := TCryptographicBuffer.Create;
try
Result := b.GenerateRandomNumber;
finally
b.Free;
end;
{$ENDIF}
{$IFDEF POSIX}
var RandomStream := TFileStream.Create('/dev/urandom', fmOpenRead);
try
RandomStream.Read(Result, SizeOf(Result));
finally
RandomStream.Free;
end;
{$ENDIF}
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment