public static SafeCertContextHandle GetCertificateContext(X509Certificate certificate)
        {
            SafeCertContextHandle certContext = X509Native.DuplicateCertContext(certificate.Handle);

            // Make sure to keep the X509Certificate object alive until after its certificate context is
            // duplicated, otherwise it could end up being closed out from underneath us before we get a
            // chance to duplicate the handle.
            GC.KeepAlive(certificate);

            return(certContext);
        }
 public static CngKey GetCngPrivateKey(X509Certificate2 certificate)
 {
     using (SafeCertContextHandle certContext = GetCertificateContext(certificate))
         using (SafeNCryptKeyHandle privateKeyHandle = X509Native.AcquireCngPrivateKey(certContext))
         {
             // We need to assert for full trust when opening the CNG key because
             // CngKey.Open(SafeNCryptKeyHandle) does a full demand for full trust, and we want to allow
             // access to a certificate's private key by anyone who has access to the certificate itself.
             new PermissionSet(PermissionState.Unrestricted).Assert();
             return(CngKey.Open(privateKeyHandle, CngKeyHandleOpenOptions.None));
         }
 }