Last active
July 27, 2020 22:16
-
-
Save DiegoQueiroz/24d9d149462e94f13cbf614654d1fd4f to your computer and use it in GitHub Desktop.
This file contains 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
uses | |
Windows, SysUtils; | |
function GeraDigitosAleatorios(tamanho: Integer): String; | |
type | |
TBCryptGenRandom = function(hAlgorithm: THandle; pbBuffer: PUCHAR; | |
cbBuffer, dwFlags: ULONG): ULONG; stdcall; | |
const | |
bcryptdll = 'bcrypt.dll'; | |
STATUS_SUCCESS = $00000000; | |
BCRYPT_USE_SYSTEM_PREFERRED_RNG = $00000002; | |
var | |
i: Integer; | |
bytes: Array of Byte; | |
BCryptLibHandle: THandle; | |
BCryptGenRandom: TBCryptGenRandom; | |
begin | |
Result := ''; | |
BCryptLibHandle := LoadLibrary(bcryptdll); | |
if BCryptLibHandle <> 0 Then | |
begin | |
try | |
@BCryptGenRandom := GetProcAddress(BCryptLibHandle, 'BCryptGenRandom'); | |
if @BCryptGenRandom <> nil Then | |
begin | |
SetLength(bytes, tamanho); | |
if STATUS_SUCCESS = BCryptGenRandom(0, @bytes[0], tamanho, | |
BCRYPT_USE_SYSTEM_PREFERRED_RNG) | |
Then | |
begin | |
for i := 0 to tamanho - 1 do | |
begin | |
Result := Result + IntToStr(bytes[i]); | |
if Length(Result) >= tamanho then break; | |
end; | |
SetLength(Result, tamanho); | |
end; | |
end; | |
finally | |
FreeLibrary(BCryptLibHandle); | |
end; | |
end; | |
if Length(Result) <> tamanho Then | |
raise Exception.Create('Falha ao gerar sequência aleatória.'); | |
end; | |
//################################## | |
// Exemplo de Utilização | |
//################################## | |
//procedure TForm1.Button1Click(Sender: TObject); | |
//begin | |
// ShowMessage(GeraDigitosAleatorios(8)); | |
//end; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment