Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use the Windows Crypto API for Pseudo-Random Data Generation

How To

Use the Windows Crypto API for Pseudo-Random Data Generation

by  Glenn9999  Posted    (Edited  )
For the unit this code uses, see faq102-7423 .

The Windows cryptography oriented functions offers use of the CS-PRNG that is included in it. Calling it will produce a number of pseudo-random bytes which can be processed afterwards for whatever purpose is necessary in the program.

Code:
function GenerateRandom(Len:Cardinal): String;
// uses the MS CSPRNG to produce Len bytes into a string.  Returns the data in
// a string of len bytes.

var
  hProv: TCryptProv;
begin
  if not CryptAcquireContext(hProv, nil, MS_ENHANCED_PROV, PROV_RSA_FULL,
         CRYPT_VERIFYCONTEXT) then
    CryptAcquireContext(hProv, nil, MS_ENHANCED_PROV, PROV_RSA_FULL,
         CRYPT_NEWKEYSET + CRYPT_VERIFYCONTEXT);
  if hProv > 0 then
    try
      SetLength(Result, Len);
      CryptGenRandom(hProv, Len, @Result[1]);
    finally
      CryptReleaseContext(hProv, 0);
    end;
end;
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top