@@ -2712,8 +2712,32 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
27122712#elif defined(USE_WINDOWS_API )
27132713
27142714#ifdef WIN_REUSE_CRYPT_HANDLE
2715- static ProviderHandle gHandle ;
2716- #endif
2715+ /* shared crypt handle for RNG use */
2716+ static ProviderHandle gHandle = 0 ;
2717+
2718+ int wc_WinCryptHandleInit (void )
2719+ {
2720+ int ret = 0 ;
2721+ if (gHandle == 0 ) {
2722+ if (!CryptAcquireContext (& gHandle , 0 , 0 , PROV_RSA_FULL ,
2723+ CRYPT_VERIFYCONTEXT )) {
2724+ DWORD dw = GetLastError ();
2725+ WOLFSSL_MSG ("CryptAcquireContext failed!" );
2726+ WOLFSSL_ERROR ((int )dw );
2727+ ret = WINCRYPT_E ;
2728+ }
2729+ }
2730+ return ret ;
2731+ }
2732+
2733+ void wc_WinCryptHandleCleanup (void )
2734+ {
2735+ if (gHandle != 0 ) {
2736+ CryptReleaseContext (gHandle , 0 );
2737+ gHandle = 0 ;
2738+ }
2739+ }
2740+ #endif /* WIN_REUSE_CRYPT_HANDLE */
27172741
27182742int wc_GenerateSeed (OS_Seed * os , byte * output , word32 sz )
27192743{
@@ -2746,22 +2770,23 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
27462770 #endif /* HAVE_INTEL_RDSEED */
27472771
27482772#ifdef WIN_REUSE_CRYPT_HANDLE
2749- if (gHandle == 0 ) {
2750- if (!CryptAcquireContext (& gHandle , 0 , 0 , PROV_RSA_FULL ,
2751- CRYPT_VERIFYCONTEXT ))
2752- return WINCRYPT_E ;
2773+ /* Check that handle was initialized.
2774+ * Note: initialization should be done through:
2775+ * wolfSSL_Init -> wolfCrypt_Init -> wc_WinCryptHandleInit
2776+ */
2777+ if (wc_WinCryptHandleInit () != 0 ) {
2778+ return WINCRYPT_E ;
27532779 }
2754- os -> handle = gHandle ;
2780+ if (!CryptGenRandom (gHandle , sz , output ))
2781+ return CRYPTGEN_E ;
27552782#else
2756- if (!CryptAcquireContext (& os -> handle , 0 , 0 , PROV_RSA_FULL ,
2757- CRYPT_VERIFYCONTEXT ))
2783+ if (!CryptAcquireContext (& os -> handle , 0 , 0 , PROV_RSA_FULL ,
2784+ CRYPT_VERIFYCONTEXT )) {
27582785 return WINCRYPT_E ;
2759- #endif
2760-
2761- if (!CryptGenRandom (os -> handle , sz , output ))
2786+ }
2787+ if (!CryptGenRandom (os -> handle , sz , output )) {
27622788 return CRYPTGEN_E ;
2763-
2764- #ifndef WIN_REUSE_CRYPT_HANDLE
2789+ }
27652790 CryptReleaseContext (os -> handle , 0 );
27662791 os -> handle = 0 ;
27672792#endif
0 commit comments