解决方法
您可以使用Windows CryptoAPI:
uses Wcrypt2; function GenerateRandom(Len: Cardinal): TBytes; var hProv : HCRYPTPROV; begin if not CryptAcquireContext(@hProv,nil,MS_ENHANCED_PROV,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT) then CryptAcquireContext(@hProv,CRYPT_NEWKEYSET + CRYPT_VERIFYCONTEXT); if hProv > 0 then try SetLength(Result,Len); CryptGenRandom(hProv,Len,@Result[0]); finally CryptReleaseContext(hProv,0); end; end;
使用上面代码的示例:
function BytesToHex(const Bytes: TBytes): string; var i : integer; begin for i := 0 to Length(Bytes)-1 do Result := Result + IntToHex(Bytes[i],2); end; procedure TForm1.Button1Click(Sender: TObject); begin ShowMessage(BytesToHex(GenerateRandom(16))); end;