public static CngKey GetCngPrivateKey(this X509Certificate2 certificate) { if (!certificate.HasPrivateKey || !certificate.HasCngKey()) { return(null); } using (SafeNCryptKeyHandle privateKeyHandle = X509Native.AcquireCngPrivateKey(certificate.Handle)) { // 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)); } }