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;