Platform SDK: Cryptography

CPGenRandom

The CPGenRandom function fills a buffer with random bytes.

BOOL CPGenRandom(
  HCRYPTPROV hProv,  // in
  DWORD dwLen,       // in
  BYTE *pbBuffer     // in, out
);

Parameters

hProv
Handle to a particular key container within the CSP. This handle is obtained with a call to CPAcquireContext.
dwLen
Number of bytes of random data to be generated.
pbBuffer
Buffer to which the function copies the random data. This buffer is dwLen bytes in length.

Upon input to the function, this buffer can contain up to dwLen bytes of random data that the CSP can use to generate a seed value. This is discussed further in Remarks.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE, and the appropriate error code from the following table must be set using SetLastError.

Error Description
NTE_BAD_UID The hProv parameter does not contain a valid context handle.
NTE_FAIL The function failed in some unexpected manner.

Remarks

CPGenRandom is one of the more difficult functions to implement correctly, and it must be done correctly to maintain the security of a CSP. CPGenRandom is used internally by the CPGenKey function, as well by applications when generating data items used in cryptographic protocols such as challenge strings. A CSP is not producing message security if values of the cryptographic keys or challenge strings produced by a CSP are predictable.

There are two components to a good random number generator: a method of getting a random seed, and an algorithm that will generate a good pseudo-random stream of data based on that seed.

Generating a random seed can depend on the hardware used by the CSP. If the CSP has access to a hardware random number source such as some slightly radioactive material and a Geiger counter, the problem is solved. A completely software-based CSP might use one of the following sources:

Some or all of this data can be hashed along with the random seed from the previous session to create a random seed. New seeds should be generated periodically throughout the session, to avoid placing too much reliance on the pseudo-random stream generator.

Once the random seed has been obtained, any number of algorithms can be used to generate a pseudo-random stream of data. Sometimes a stream cipher such as RC4 is used for this purpose, with the seed forming the keying material. The following sources describe other algorithms and techniques:

Requirements

  Windows NT/2000: Requires Windows NT 4.0 or later.
  Windows 95/98: Requires Windows 95 OSR2 or later (or Windows 95 with Internet Explorer 3.02 or later).
  Header: Declared in Wincrypt.h.

See Also

CryptGenRandom