Delphi 随机指定长度字节
unit Unit1; interface uses Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; const PROV_RSA_FULL = 1; CRYPT_VERIFYCONTEXT = $F0000000; type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; HCRYPTPROV = ULONG_PTR; PHCRYPTPROV = ^HCRYPTPROV; // 导入外部函数 function CryptAcquireContext(phProv: PHCRYPTPROV; pszContainer: PChar; pszProvider: PChar; dwProvType: DWORD; dwFlags: DWORD): BOOL; stdcall; external 'advapi32.dll' name 'CryptAcquireContextA'; function CryptGenRandom(hProv: HCRYPTPROV; dwLen: DWORD; pbBuffer: Pointer): BOOL; stdcall; external 'advapi32.dll' name 'CryptGenRandom'; function CryptReleaseContext(hProv: HCRYPTPROV; dwFlags: DWORD): BOOL; stdcall; external 'advapi32.dll' name 'CryptReleaseContext'; var Form1: TForm1; implementation {$R *.dfm} function GenerateRandomBytes(NumBytes: Integer): TBytes; var hProv: HCRYPTPROV; Buffer: TBytes; begin SetLength(Buffer, NumBytes); // 获取加密上下文 if not CryptAcquireContext(@hProv, nil, nil, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) then raise Exception.Create('CryptAcquireContext failed with error: ' + IntToStr(GetLastError)); try // 生成加密安全的随机字节 if not CryptGenRandom(hProv, NumBytes, @Buffer[0]) then raise Exception.Create('CryptGenRandom failed with error: ' + IntToStr(GetLastError)); finally // 释放加密上下文 CryptReleaseContext(hProv, 0); end; Result := Buffer; end; procedure TForm1.Button1Click(Sender: TObject); var RandomBytes: TBytes; begin RandomBytes:=GenerateRandomBytes(64); end; end.
非伪随机.
目录 返回
首页