@@ -2711,6 +2711,34 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
27112711
27122712#elif defined(USE_WINDOWS_API )
27132713
2714+ #ifdef WIN_REUSE_CRYPT_HANDLE
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 */
2741+
27142742int wc_GenerateSeed (OS_Seed * os , byte * output , word32 sz )
27152743{
27162744#ifdef WOLF_CRYPTO_CB
@@ -2741,14 +2769,27 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
27412769 }
27422770 #endif /* HAVE_INTEL_RDSEED */
27432771
2744- if (!CryptAcquireContext (& os -> handle , 0 , 0 , PROV_RSA_FULL ,
2745- CRYPT_VERIFYCONTEXT ))
2772+ #ifdef WIN_REUSE_CRYPT_HANDLE
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 ) {
27462778 return WINCRYPT_E ;
2747-
2748- if (!CryptGenRandom (os -> handle , sz , output ))
2779+ }
2780+ if (!CryptGenRandom (gHandle , sz , output ))
27492781 return CRYPTGEN_E ;
2750-
2782+ #else
2783+ if (!CryptAcquireContext (& os -> handle , 0 , 0 , PROV_RSA_FULL ,
2784+ CRYPT_VERIFYCONTEXT )) {
2785+ return WINCRYPT_E ;
2786+ }
2787+ if (!CryptGenRandom (os -> handle , sz , output )) {
2788+ return CRYPTGEN_E ;
2789+ }
27512790 CryptReleaseContext (os -> handle , 0 );
2791+ os -> handle = 0 ;
2792+ #endif
27522793
27532794 return 0 ;
27542795}
0 commit comments