void AssertHasPrivateKeyRights(CryptoKeySecurity privateKeySecurity, string identifier, CryptoKeyRights right) { var accessRules = privateKeySecurity.GetAccessRules(true, false, typeof(NTAccount)); var found = accessRules.Cast <CryptoKeyAccessRule>() .Any(x => x.IdentityReference.Value == identifier && x.CryptoKeyRights.HasFlag(right)); Assert.True(found, "Private-Key right was not set"); }
void RemoveCertificatePrivateKeyAccess(X509Certificate2 cert) { if (cert != null && cert.HasPrivateKey) { try { AsymmetricAlgorithm key = cert.PrivateKey; // Only RSA provider is supported here if (key is RSACryptoServiceProvider) { RSACryptoServiceProvider prov = key as RSACryptoServiceProvider; CspKeyContainerInfo info = prov.CspKeyContainerInfo; CryptoKeySecurity keySec = info.CryptoKeySecurity; SecurityIdentifier ns = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null); AuthorizationRuleCollection rules = keySec.GetAccessRules(true, false, typeof(SecurityIdentifier)); foreach (AuthorizationRule rule in rules) { CryptoKeyAccessRule keyAccessRule = (CryptoKeyAccessRule)rule; if (keyAccessRule.AccessControlType == AccessControlType.Allow && (int)(keyAccessRule.CryptoKeyRights & CryptoKeyRights.GenericRead) != 0) { SecurityIdentifier sid = keyAccessRule.IdentityReference as SecurityIdentifier; if (ns.Equals(sid)) { CryptoKeyAccessRule nsReadRule = new CryptoKeyAccessRule(ns, CryptoKeyRights.GenericRead, AccessControlType.Allow); keySec.RemoveAccessRule(nsReadRule); CommitCryptoKeySecurity(info, keySec); break; } } } } } #pragma warning suppress 56500 catch (Exception e) { // CommitCryptoKeySecurity can actually throw any exception, // so the safest way here is to catch a generic exception while throw on critical ones if (Utilities.IsCriticalException(e)) { throw; } throw new WsatAdminException(WsatAdminErrorCode.CANNOT_UPDATE_PRIVATE_KEY_PERM, SR.GetString(SR.ErrorUpdateCertPrivateKeyPerm), e); } } }