static CryptoKeySecurity GetCspPrivateKeySecurity(SafeCertContextHandle certificate)
 {
     using (var cspHandle = CertificatePal.GetCspPrivateKey(certificate))
     {
         var security = new CryptoKeySecurity();
         security.SetSecurityDescriptorBinaryForm(CertificatePal.GetCspPrivateKeySecurity(cspHandle), AccessControlSections.Access);
         return(security);
     }
 }
        static void SetCspPrivateKeySecurity(SafeCertContextHandle certificate, ICollection <PrivateKeyAccessRule> accessRules)
        {
            using (var cspHandle = CertificatePal.GetCspPrivateKey(certificate))
            {
                var security = GetCspPrivateKeySecurity(certificate);

                foreach (var cryptoKeyAccessRule in accessRules.Select(r => r.ToCryptoKeyAccessRule()))
                {
                    security.AddAccessRule(cryptoKeyAccessRule);
                }

                var securityDescriptorBytes = security.GetSecurityDescriptorBinaryForm();

                if (!CryptSetProvParam(cspHandle, CspProperties.SecurityDescriptor,
                                       securityDescriptorBytes, SecurityDesciptorParts.DACL_SECURITY_INFORMATION))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
            }
        }