Is CryptGenRandom() thread-safe with a single global program-wide HCRYPTPROV instance?
MSDN appears to lack any info on this: https://msdn.microsoft.com/en-us/library/windows/desktop/aa379942(v=vs.85).aspx
Creating a separate HCRYPTPROV per thread and destroying it again would significantly complicate matters (and also risk more security-relevant bugs on my side), so this would be really useful to know. Sharing one global HCRYPTPROV would be a lot easier for sure.
So does anyone here know about the thread-safety of CryptGenRandom(), particularly with a single HCRYPTPROV instance?
Creating a separate
HCRYPTPROVper thread doesn't make much sense. This is pointer to memory block from heap in all current implementations, primarily saved pointers to CSP entry points which used to call actual provider implementation (CPGenRandomin our case). The references themselves do not contain state of the CSP, unlike for exampleHCRYPTKEYwhich containing actual key state. So even if you create a separateHCRYPTPROVfor every thread - this changes nothing.There may be some global variables / data used by CSP internally during this call; this is however unknown as these would be implementation details. Of course we can serialize calls to
CryptGenRandomin the code. However we cannot control that some other dll in our process also callCryptGenRandomconcurrently. So serializing all calls toCryptGenRandomalso impossible.As result I think the
CPGenRandommust be design to be thread-safe. and it my tests with a well known Microsoft CSP this is true. Internal synchronization is used in function, when need access global data and if multiple threads callCPGenRandomconcurrently; every thread receives unique random data.So my conclusion -
CryptGenRandomis thread-safe, at least for all Microsoft CSP