Implement arc4random_buf on bsd
Author: sikofitt <sikofitt@gmail.com>
This commit is contained in:
parent
d9678a6260
commit
2c8d71aed1
|
@ -48,6 +48,7 @@ uses
|
||||||
Renegade.Random.URandom;
|
Renegade.Random.URandom;
|
||||||
|
|
||||||
type
|
type
|
||||||
|
PCChar = ^CChar;
|
||||||
PBSDRandom = ^BSDRandom;
|
PBSDRandom = ^BSDRandom;
|
||||||
BSDRandom = class (RandomTrait, RandomInterface)
|
BSDRandom = class (RandomTrait, RandomInterface)
|
||||||
private
|
private
|
||||||
|
@ -57,20 +58,25 @@ type
|
||||||
function GetString(NBytes : SizeUInt) : AnsiString;
|
function GetString(NBytes : SizeUInt) : AnsiString;
|
||||||
end;
|
end;
|
||||||
|
|
||||||
procedure arc4random_buf(var Buffer : PCChar; StringLength : CInt);
|
procedure arc4random_buf(var Buffer; NBytes : csize_t);
|
||||||
cdecl;varargs;external 'c' name 'arc4random_buf';
|
cdecl;external 'c' name 'arc4random_buf';
|
||||||
|
|
||||||
implementation
|
implementation
|
||||||
|
|
||||||
function GetSystemBytes(var RandomByteBuffer : TBytes; NBytes : SizeUint) : CInt;
|
function BSDRandom.GetSystemBytes(var RandomByteBuffer : TBytes; NBytes : SizeUint) : CInt;
|
||||||
|
var
|
||||||
|
CharBuffer : array of pcuint8;
|
||||||
begin
|
begin
|
||||||
arc4random_buf(@RandomByteBuffer^, NBytes);
|
SetLength(CharBuffer, NBytes);
|
||||||
if Length(RandomByteBuffer^) <> NBytes then
|
arc4random_buf(CharBuffer[0], NBytes);
|
||||||
|
if Length(CharBuffer) <> NBytes then
|
||||||
begin
|
begin
|
||||||
|
RandomByteBuffer[0] := 0;
|
||||||
Result := -1;
|
Result := -1;
|
||||||
end else
|
end else
|
||||||
begin
|
begin
|
||||||
Result := Length(RandomByteBuffer^);
|
Move(CharBuffer[Low(CharBuffer)], RandomByteBuffer[0], NBytes);
|
||||||
|
Result := High(RandomByteBuffer);
|
||||||
end;
|
end;
|
||||||
end;
|
end;
|
||||||
|
|
||||||
|
@ -78,6 +84,7 @@ function BSDRandom.GetBytes(NBytes : SizeUInt) : TBytes;
|
||||||
var
|
var
|
||||||
RandomBuffer : AnsiString;
|
RandomBuffer : AnsiString;
|
||||||
begin
|
begin
|
||||||
|
SetLength(RandomBuffer, NBytes);
|
||||||
SetLength(Result, NBytes);
|
SetLength(Result, NBytes);
|
||||||
RandomBuffer := GetString(NBytes);
|
RandomBuffer := GetString(NBytes);
|
||||||
Move(RandomBuffer[1], Result[0], NBytes);
|
Move(RandomBuffer[1], Result[0], NBytes);
|
||||||
|
@ -85,11 +92,13 @@ end;
|
||||||
|
|
||||||
function BSDRandom.GetString(NBytes : SizeUInt) : AnsiString;
|
function BSDRandom.GetString(NBytes : SizeUInt) : AnsiString;
|
||||||
var
|
var
|
||||||
TURandom : URandom;
|
RandomBuffer : TBytes;
|
||||||
|
B : SizeInt;
|
||||||
begin
|
begin
|
||||||
TURandom := URandom.Create;
|
SetLength(RandomBuffer, (NBytes*2));
|
||||||
SetLength(Result, NBytes);
|
SetLength(Result, NBytes);
|
||||||
Result := TURandom.GetString(NBytes);
|
B := GetSystemBytes(RandomBuffer, (NBytes*2));
|
||||||
|
Move(RandomBuffer[0], Result[1], NBytes);
|
||||||
end;
|
end;
|
||||||
|
|
||||||
end.
|
end.
|
||||||
|
|
Loading…
Reference in New Issue