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 (or "context") within the CSP. This handle is obtained via a call to CPAcquireContext.
dwLen
Number of bytes of random data to be generated.
pbBuffer
Buffer to which the function is to copy the random data. This buffer is dwLen bytes in length.

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

Return Values

If the function succeeds, TRUE should be returned; otherwise, return FALSE. When FALSE is returned, the appropriate error code (see the following table) must be set via 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

Although CPGenRandom is one of the more difficult functions to implement correctly, it must be done correctly to maintain the security of your CSP. The CPGenRandom function is (typically) used internally by the CPGenKey function, as well by applications when generating data items used in cryptographic protocols, such as challenge strings. If the value of the cryptographic keys or challenge strings produced by your CSP is in any way predictable, then your CSP is not doing its job.

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

Generating a truly random seed can be difficult, depending on the hardware that your CSP is running on. If your CSP has access to a hardware random number source (such as some slightly radioactive material and a Geiger counter), then this doesn't present much of a problem. If your CSP is completely software-based, some of the following sources may be used:

All of this data can be hashed together, along with the random seed from the previous session, to make a fairly good random seed. A new seed 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 based on it. 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:

See Also

CryptGenRandom