title: BCryptGenRandom STATUS_INVALID_HANDLE
body: <p>I am trying to generate cryptographically secure numbers in Windows. I have the following code:</p>
  
  <pre><code>#ifndef w64crypt
  #define w64crypt
  #include &lt;windows.h&gt;
  #include &lt;bcrypt.h&gt;
  unsigned long getSeed(ULONG buffer_size){ 
      NTSTATUS status=0;
      ULONG flags=0;
      PUCHAR c_seed;
      BCRYPT_ALG_HANDLE handle;
      status=BCryptOpenAlgorithmProvider(
              &amp;handle,BCRYPT_RNG_ALGORITHM,NULL,0
      );
      if(!BCRYPT_SUCCESS(status)){
              cout &lt;&lt; "BCryptOpenAlgorithmProvider";
              printf("%X",status);
      }
      status=BCryptGenRandom(
              handle,c_seed,128,0
      );
      if(!BCRYPT_SUCCESS(status)){
              cout &lt;&lt; "Error in BCryptGenRandom";
              printf("%X",status);
      }
      status=BCryptCloseAlgorithmProvider(
              handle,0
      );
      if(!BCRYPT_SUCCESS(status)){
              cout &lt;&lt; "BCryptCloseAlgorithmProvider";
              printf("%X",status);
      }
      unsigned long seedNo=(unsigned long)c_seed;
      return seedNo;
  }
  #endif
  </code></pre>
  
  <p>When I run this, I get <code>Error in BCryptGenRandom C0000008</code>, which is <code>STATUS_INVALID_HANDLE</code>. This is what the documentation calls for:</p>
  
  <p><a href="https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptopenalgorithmprovider" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptopenalgorithmprovider</a></p>
  
  <pre><code>NTSTATUS BCryptOpenAlgorithmProvider(
    BCRYPT_ALG_HANDLE *phAlgorithm,
    LPCWSTR           pszAlgId,
    LPCWSTR           pszImplementation,
    ULONG             dwFlags
  );
  </code></pre>
  
  <p><a href="https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom</a></p>
  
  <pre><code>NTSTATUS BCryptGenRandom(
    BCRYPT_ALG_HANDLE hAlgorithm,
    PUCHAR            pbBuffer,
    ULONG             cbBuffer,
    ULONG             dwFlags
  );
  </code></pre>
  
  <p>The above link also states that <code>pszAlgId</code> must be:</p>
  
  <blockquote>
    <p>The handle of an algorithm provider created by using the BCryptOpenAlgorithmProvider function. The algorithm that was specified when the provider was created must support the random number generator interface.</p>
  </blockquote>
  
  <p>Looking at <a href="https://docs.microsoft.com/en-us/windows/win32/seccng/cng-algorithm-identifiers" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/windows/win32/seccng/cng-algorithm-identifiers</a>, <code>BCRYPT_RNG_ALGORITHM</code> is my ideal candidate.</p>
  
  <p>I'm compiling this using <code>mingw-w64</code>, cross-compiling from Ubuntu 18.04.</p>
  
  <p>Why am I receiving this <code>NTSTATUS</code>?</p>