private void ThrowBetterException(bool keyMustExist) { SafeCryptContextHandle hProv = null; int success = 0; try { success = UnsafeNativeMethods.CryptAcquireContext(out hProv, KeyContainerName, CspProviderName, PROV_Rsa_FULL, UseMachineContainer ? CRYPT_MACHINE_KEYSET : 0); if (success != 0) { return; // propagate original exception } int hr = Marshal.GetHRForLastWin32Error(); if (hr == HResults.NteBadKeySet && !keyMustExist) { return; // propagate original exception } switch (hr) { case HResults.NteBadKeySet: case HResults.Win32AccessDenied: case HResults.Win32InvalidHandle: throw new ConfigurationErrorsException(SR.GetString(SR.Key_container_doesnt_exist_or_access_denied)); default: Marshal.ThrowExceptionForHR(hr); break; } } finally { if (!(hProv == null || hProv.IsInvalid)) { hProv.Dispose(); } } }
private void ThrowBetterException(bool keyMustExist) { SafeCryptContextHandle phProv = null; try { if (Microsoft.Win32.UnsafeNativeMethods.CryptAcquireContext(out phProv, this.KeyContainerName, this.CspProviderName, 1, this.UseMachineContainer ? 0x20 : 0) == 0) { int errorCode = Marshal.GetHRForLastWin32Error(); if ((errorCode != -2146893802) || keyMustExist) { switch (errorCode) { case -2147024891: case -2147024890: case -2146893802: throw new ConfigurationErrorsException(System.Configuration.SR.GetString("Key_container_doesnt_exist_or_access_denied")); } Marshal.ThrowExceptionForHR(errorCode); } } } finally { if ((phProv != null) && !phProv.IsInvalid) { phProv.Dispose(); } } }