问题
I swear, this seems to be changing every time I check the MSDN documentation. When I coded my executable Microsoft was suggesting to use RtlGenRandom API to generate cryptographically strong random numbers.
Now when I'm checking documentation for RtlGenRandom, the note there suggests using CryptGenRandom instead. But then another note for CryptGenRandom states this:
Important: This API is deprecated. New and existing software should start using Cryptography Next Generation APIs. Microsoft may remove this API in future releases.
So can someone show an example in C of how to use those "Cryptography Next Generation APIs" to generate a byte array of random numbers that Microsoft recommends now?
回答1:
It does not really matter, on Windows XP and later the default providers end up calling the same function. The RNG on 2000 and unpatched XP mainly use SHA1+RC4 internally and it has some security issues.
I just did some experiments on Windows 8 and this is what I found:
RtlGenRandom
(AKAadvapi32!SystemFunction036
) callsCRYPTBASE!SystemFunction036
>>>bcryptPrimitives!ProcessPrng
>>>bcryptPrimitives!AesRNG*
.CryptGenRandom
callsCRYPTSP!CryptGenRandom
>>>%provider%!CPGenRandom
>>>CRYPTBASE!SystemFunction036
.%provider%
was rsaenh or dssenh in my tests but could possibly be a different implementation if you specifically ask for a 3rd-party provider.BCryptGenRandom
callsbcryptPrimitives!MSCryptGenRandom
>>>bcryptPrimitives!GenRandomAes
>>>bcryptPrimitives!AesRNG*
with theBCRYPT_RNG_ALGORITHM
CNG Algorithm Identifier (BCRYPT_RNG_DUAL_EC_ALGORITHM
ends up inbcryptPrimitives!GenRandomDualEcc
instead).
This is of course undocumented implementation details that could change but I don't really think you need to worry about which function you pick. If your target is Vista+ you can use BCrypt. CryptGenRandom
will never be removed, it would break too many applications and you should pick it if you support < Vista.
来源:https://stackoverflow.com/questions/48875929/rtlgenrandom-cryptgenrandom-or-other-winapi-to-generate-cryptographically-secure