Last active
September 10, 2024 08:22
-
-
Save jimmckeeth/2c66e7c4fee55d56ad9928606f6cc197 to your computer and use it in GitHub Desktop.
Delphi Cryptographically Secure Random Number Generator that works on all paltforms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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