forked from martinusso/ulid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiPlatformCryptoRandom.pas
More file actions
52 lines (42 loc) · 1.03 KB
/
MultiPlatformCryptoRandom.pas
File metadata and controls
52 lines (42 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Tested on Windows, MacOS, Linux, and Android. From what I've read /dev/urandom works on iOS too.
// https://gist.github.com/jimmckeeth/2c66e7c4fee55d56ad9928606f6cc197
unit MultiPlatformCryptoRandom;
interface
uses System.Classes, System.SysUtils;
function CryptoRandomCardinal: Cardinal;
function CryptoRandomFloat: Single;
function CryptoRandomRange(max: Cardinal): Cardinal;
implementation
{$IFDEF MSWindows}
uses WinAPI.Security.Cryptography;
{$ENDIF}
function CryptoRandomRange(max: Cardinal): Cardinal;
begin
Result := CryptoRandomCardinal mod max;
end;
function CryptoRandomFloat: Single;
begin
Result := CryptoRandomCardinal / 4294967295;
end;
function CryptoRandomCardinal: 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.