public async Task <CertificateOperation> CreateCertificateAsync(
            string certificateName,
            string certificateCN,
            IDictionary <string, string> tags   = null,
            CancellationToken cancellationToken = default
            )
        {
            try {
                tags ??= new Dictionary <string, string>();

                Log.Information($"Adding certificate to Azure KeyVault: {certificateName} ...");

                // ToDo: Add support of PEM certificate creation: CertificateContentType.Pem
                var contentType = CertificateContentType.Pfx;

                var certificatePolicy = new CertificatePolicy {
                    KeyProperties = new KeyProperties {
                        Exportable = true,
                        KeyType    = "RSA",
                        KeySize    = 2048,
                        ReuseKey   = false
                    },
                    SecretProperties = new SecretProperties {
                        ContentType = contentType
                    },
                    X509CertificateProperties = new X509CertificateProperties {
                        Subject = $"CN={certificateCN}",
                        SubjectAlternativeNames = new SubjectAlternativeNames {
                            DnsNames = new string[] { certificateCN }
                        }
                    },
                    IssuerParameters = new IssuerParameters {
                        Name = "Self"
                    }
                };

                certificatePolicy.Validate();

                var certificateAttributes = new CertificateAttributes();

                var certificateOperation = await _keyVaultClient
                                           .CreateCertificateAsync(
                    _keyVault.Properties.VaultUri,
                    certificateName,
                    certificatePolicy,
                    certificateAttributes,
                    tags,
                    cancellationToken
                    );

                Log.Information($"Added certificate to Azure KeyVault: {certificateName}");

                return(certificateOperation);
            }
            catch (Exception ex) {
                Log.Error(ex, $"Failed to add certificate to Azure KeyVault: {certificateName}");
                throw;
            }
        }
 private async Task <CertificateBundle> ImportCertificateAsync(
     string certificateBase64,
     string password,
     CertificateAttributes attributes,
     CancellationToken cancellationToken)
 {
     return(await _keyVaultClient.ImportCertificateAsync($"https://{Name}.vault.azure.net", _certificateName, certificateBase64, password, certificateAttributes : attributes, cancellationToken : cancellationToken));
 }
        public async Task <ICertificate> UploadAsync(byte[] pfxBytes, string password, string[] hostNames, CancellationToken cancellationToken)
        {
            var cert   = LoadFrom(pfxBytes, password);
            var base64 = Convert.ToBase64String(pfxBytes);
            var now    = DateTime.UtcNow;
            var attr   = new CertificateAttributes(true, cert.NotBefore, cert.NotAfter, now);
            var r      = await ImportCertificateAsync(base64, password, attr, cancellationToken);

            return(new CertificateInfo(r, this));
        }
Beispiel #4
0
        private CertificateAttributes CreateCertificateAttributes(DateTime notBefore, DateTime notAfter)
        {
            var attributes = new CertificateAttributes
            {
                Enabled   = true,
                NotBefore = notBefore,
                Expires   = notAfter
            };

            return(attributes);
        }
        public override async Task <ListViewItemBase> ResetExpirationAsync(CancellationToken cancellationToken)
        {
            var ca = new CertificateAttributes()
            {
                NotBefore = (this.NotBefore == null) ? (DateTime?)null : DateTime.UtcNow.AddHours(-1),
                Expires   = (this.Expires == null) ? (DateTime?)null : DateTime.UtcNow.AddYears(1)
            };
            CertificateBundle cb = await Session.CurrentVault.UpdateCertificateAsync(Name, null, null, ca, Tags, cancellationToken); // Reset only NotBefore and Expires attributes

            return(new ListViewItemCertificate(Session, cb));
        }
        public void CertificateAttribute_Count()
        {
            {
                var test = new CertificateAttributes
                {
                    CommonName          = "CommonName",
                    OrganisationalUnits = new List <string>
                    {
                        "OU0",
                        "OU1",
                        "OU2"
                    },
                    Organisation = "Organisation"
                };
                Assert.AreEqual(5, test.Count);
            }

            {
                var test = new CertificateAttributes
                {
                    OrganisationalUnits = new List <string>
                    {
                        "OU0",
                        "OU1",
                        "OU2"
                    },
                    Organisation = "Organisation"
                };
                Assert.AreEqual(4, test.Count);
            }

            {
                var test = new CertificateAttributes
                {
                    Organisation = "Organisation"
                };
                Assert.AreEqual(1, test.Count);
            }

            {
                var test = new CertificateAttributes
                {
                    CommonName   = "CommonName",
                    Organisation = "Organisation"
                };
                Assert.AreEqual(2, test.Count);
            }
        }
        /// <summary>
        /// Create certificate
        /// </summary>
        /// <param name="certificateName"></param>
        /// <param name="policy"></param>
        /// <param name="attributes"></param>
        /// <param name="tags"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        private async Task <CertificateOperation> CreateCertificateAsync(
            string certificateName, CertificatePolicy policy,
            CertificateAttributes attributes, IDictionary <string, string> tags,
            CancellationToken ct)
        {
            var operation = await _keyVaultClient.CreateCertificateAsync(
                _vaultBaseUrl, certificateName, policy, attributes, tags, ct);

            while (operation.Status.EqualsIgnoreCase("inprogress"))
            {
                await Task.Delay(1000, ct);

                ct.ThrowIfCancellationRequested();
                operation = await _keyVaultClient.GetCertificateOperationAsync(
                    _vaultBaseUrl, certificateName, ct);
            }
            if (!operation.Status.EqualsIgnoreCase("completed"))
            {
                throw new CryptographicUnexpectedOperationException(
                          $"Failed to create certificate - Status {operation.Status}");
            }
            return(operation);
        }
Beispiel #8
0
        public static CertificateAttributes ParseCertificateAttributesString(string attributes)
        {
            CertificateAttributes certAttributes = new CertificateAttributes();

            var tokens = attributes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim());

            foreach (var t in tokens)
            {
                if (t.StartsWith("CN=", StringComparison.InvariantCultureIgnoreCase))
                {
                    certAttributes.CommonName = t.Substring(3).Trim();
                }
                else if (t.StartsWith("OU=", StringComparison.InvariantCultureIgnoreCase))
                {
                    certAttributes.OrganisationalUnits.Add(t.Substring(3).Trim());
                }
                else if (t.StartsWith("O=", StringComparison.InvariantCultureIgnoreCase))
                {
                    certAttributes.Organisation = t.Substring(2).Trim();
                }
            }

            return(certAttributes);
        }
 private ListViewItemCertificate(ISession session, CertificateIdentifier identifier, CertificateAttributes attributes, string thumbprint, IDictionary <string, string> tags) :
     base(session, KeyVaultCertificatesGroup, identifier, tags, attributes.Enabled, attributes.Created, attributes.Updated, attributes.NotBefore, attributes.Expires)
 {
     Attributes = attributes;
     Thumbprint = thumbprint?.ToLowerInvariant();
 }
Beispiel #10
0
        /// <summary>
        /// Merges a certificate or a certificate chain with a key pair existing on the server.
        /// </summary>
        /// <param name="vaultBaseUrl">The URL for the vault containing the certificate</param>
        /// <param name="certificateName">The name of the certificate</param>
        /// <param name="x509Certificates">The certificate or the certificte chain to merge</param>
        /// <param name="certificateAttributes">The attributes of the certificate (optional)</param>
        /// <param name="tags">Application-specific metadata in the form of key-value pairs</param>
        /// <param name="cancellationToken">Optional cancellation token</param>
        /// <returns>A response message containing the merged certificate.</returns>
        public static async Task <CertificateBundle> MergeCertificateAsync(this IKeyVaultClient operations, string vaultBaseUrl, string certificateName, X509Certificate2Collection x509Certificates, CertificateAttributes certificateAttributes = null, IDictionary <string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrWhiteSpace(vaultBaseUrl))
            {
                throw new ArgumentNullException(nameof(vaultBaseUrl));
            }

            if (string.IsNullOrWhiteSpace(certificateName))
            {
                throw new ArgumentNullException(nameof(certificateName));
            }

            if (x509Certificates == null || x509Certificates.Count == 0)
            {
                throw new ArgumentException("x509Certificates");
            }

            var X5C = new List <byte[]>();

            foreach (var cert in x509Certificates)
            {
                X5C.Add(cert.Export(X509ContentType.Cert));
            }

            using (var _result = await operations.MergeCertificateWithHttpMessagesAsync(vaultBaseUrl, certificateName, X5C, certificateAttributes, tags, null, cancellationToken))
            {
                return(_result.Body);
            }
        }
Beispiel #11
0
        /// <summary>
        /// Imports a new certificate version. If this is the first version, the certificate resource is created.
        /// </summary>
        /// <param name="vaultBaseUrl">The URL for the vault containing the certificate</param>
        /// <param name="certificateName">The name of the certificate</param>
        /// <param name="certificateCollection">The certificate collection with the private key</param>
        /// <param name="certificatePolicy">The management policy for the certificate</param>
        /// <param name="certificateAttributes">The attributes of the certificate (optional)</param>
        /// <param name="tags">Application-specific metadata in the form of key-value pairs</param>
        /// <param name="cancellationToken">Optional cancellation token</param>
        /// <returns>Imported certificate bundle to the vault.</returns>
        public static async Task <CertificateBundle> ImportCertificateAsync(this IKeyVaultClient operations, string vaultBaseUrl, string certificateName, X509Certificate2Collection certificateCollection, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes = null, IDictionary <string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrWhiteSpace(vaultBaseUrl))
            {
                throw new ArgumentNullException(nameof(vaultBaseUrl));
            }

            if (string.IsNullOrWhiteSpace(certificateName))
            {
                throw new ArgumentNullException(nameof(certificateName));
            }

            if (null == certificateCollection)
            {
                throw new ArgumentNullException(nameof(certificateCollection));
            }

            var base64EncodedCertificate = Convert.ToBase64String(certificateCollection.Export(X509ContentType.Pfx));

            using (var _result = await operations.ImportCertificateWithHttpMessagesAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, string.Empty, certificatePolicy, certificateAttributes, tags, null, cancellationToken))
            {
                return(_result.Body);
            }
        }
Beispiel #12
0
        /// <summary>
        /// Updates a certificate version.
        /// </summary>
        /// <param name="certificateIdentifier">The URL for the certificate.</param>
        /// <param name='certificatePolicy'>The management policy for the certificate.</param>
        /// <param name="certificateAttributes">The attributes of the certificate (optional)</param>
        /// <param name="tags">Application-specific metadata in the form of key-value pairs</param>
        /// <param name="cancellationToken">Optional cancellation token</param>
        /// <returns>The updated certificate.</returns>
        public static async Task <CertificateBundle> UpdateCertificateAsync(this IKeyVaultClient operations, string certificateIdentifier, CertificatePolicy certificatePolicy = default(CertificatePolicy), CertificateAttributes certificateAttributes = null, IDictionary <string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrWhiteSpace(certificateIdentifier))
            {
                throw new ArgumentNullException(nameof(certificateIdentifier));
            }

            var certId = new CertificateIdentifier(certificateIdentifier);

            using (var _result = await operations.UpdateCertificateWithHttpMessagesAsync(certId.Vault, certId.Name, certId.Version ?? string.Empty, certificatePolicy, certificateAttributes, tags, null, cancellationToken).ConfigureAwait(false))
            {
                return(_result.Body);
            }
        }
        /// <summary>
        /// Updates a certificate
        /// </summary>
        /// <param name="certificateName">The name of the certificate in the given vault.</param>
        /// <param name="certificateVersion">The certificate version (optional)</param>
        /// <param name="certificatePolicy">The certificate policy (optional)</param>
        /// <param name="certificateAttributes">The attributes of the certificate (optional)</param>
        /// <param name="tags">Application-specific metadata in the form of key-value pairs</param>
        /// <param name="cancellationToken">Optional cancellation token</param>
        /// <returns>A response message containing the updated certificate.</returns>
        public async Task <CertificateBundle> UpdateCertificateAsync(string certificateName, string certificateVersion = null, CertificatePolicy certificatePolicy = null, CertificateAttributes certificateAttributes = null, IDictionary <string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            tags = Utils.AddMd5ChangedBy(tags, null, AuthenticatedUserName);
            certificateVersion = certificateVersion ?? string.Empty;
            var t0 = _keyVaultClients[0].UpdateCertificateAsync(_keyVaultClients[0].VaultUri, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags, cancellationToken);
            var t1 = Secondary ? _keyVaultClients[1].UpdateCertificateAsync(_keyVaultClients[1].VaultUri, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags, cancellationToken) : CompletedTask;
            await Task.WhenAll(t0, t1).ContinueWith((t) =>
            {
                if (t0.IsFaulted && t1.IsFaulted)
                {
                    throw new SecretException($"Failed to update certificate {certificateName} in both vaults {_keyVaultClients[0]} and {_keyVaultClients[1]}", t0.Exception, t1.Exception);
                }
                if (t0.IsFaulted)
                {
                    throw new SecretException($"Failed to update certificate {certificateName} in vault {_keyVaultClients[0]}", t0.Exception);
                }
                if (t1.IsFaulted)
                {
                    throw new SecretException($"Failed to update certificate {certificateName} in vault {_keyVaultClients[1]}", t1.Exception);
                }
            });

            return(t0.Result);
        }
        /// <summary>
        /// Imports a new certificate version. If this is the first version, the certificate resource is created.
        /// </summary>
        /// <param name="certificateName">The name of the certificate</param>
        /// <param name="certificateCollection">The certificate collection with the private key</param>
        /// <param name="certificatePolicy">The management policy for the certificate</param>
        /// <param name="certificateAttributes">The attributes of the certificate (optional)</param>
        /// <param name="tags">Application-specific metadata in the form of key-value pairs</param>
        /// <param name="cancellationToken">Optional cancellation token</param>
        /// <returns>A response message containing the imported certificate.</returns>
        public async Task <CertificateBundle> ImportCertificateAsync(string certificateName, X509Certificate2Collection certificateCollection, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes = null, IDictionary <string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            string thumbprint = certificateCollection.Cast <X509Certificate2>().FirstOrDefault()?.Thumbprint.ToLowerInvariant();

            tags = Utils.AddMd5ChangedBy(tags, thumbprint, AuthenticatedUserName);
            var t0 = _keyVaultClients[0].ImportCertificateAsync(_keyVaultClients[0].VaultUri, certificateName, certificateCollection, certificatePolicy, certificateAttributes, tags, cancellationToken);
            var t1 = Secondary ? _keyVaultClients[1].ImportCertificateAsync(_keyVaultClients[1].VaultUri, certificateName, certificateCollection, certificatePolicy, certificateAttributes, tags, cancellationToken) : CompletedTask;
            await Task.WhenAll(t0, t1).ContinueWith((t) =>
            {
                if (t0.IsFaulted && t1.IsFaulted)
                {
                    throw new SecretException($"Failed to import certificate {certificateName} to both vaults {_keyVaultClients[0]} and {_keyVaultClients[1]}", t0.Exception, t1.Exception);
                }
                if (t0.IsFaulted)
                {
                    throw new SecretException($"Failed to import certificate {certificateName} to vault {_keyVaultClients[0]}", t0.Exception);
                }
                if (t1.IsFaulted)
                {
                    throw new SecretException($"Failed to import certificate {certificateName} to vault {_keyVaultClients[1]}", t1.Exception);
                }
            });

            return(t0.Result);
        }
        /// <inheritdoc/>
        public async Task <Certificate> NewRootCertificateAsync(string certificateName,
                                                                X500DistinguishedName subjectName, DateTime?notBefore, TimeSpan lifetime,
                                                                CreateKeyParams keyParams, IssuerPolicies policies,
                                                                Func <byte[], IEnumerable <X509Extension> > extensions,
                                                                CancellationToken ct)
        {
            if (string.IsNullOrEmpty(certificateName))
            {
                throw new ArgumentNullException(nameof(certificateName));
            }

            // Validate policies
            policies = policies.Validate(null, keyParams);
            string caTempCertIdentifier = null;

            try {
                // (1) Create key in key vault and get CSR.

                // policy self signed, new key, not exportable key
                var policySelfSignedNewKey = CreateCertificatePolicy(
                    subjectName.Name, keyParams, true, _keyStoreIsHsm, false, false);
                var tempAttributes = CreateCertificateAttributes(
                    DateTime.UtcNow.AddMinutes(-10), TimeSpan.FromMinutes(10),
                    DateTime.MaxValue);

                await CreateCertificateAsync(certificateName, policySelfSignedNewKey,
                                             tempAttributes, null, ct);

                // We have the cert - get it and key identifier to do the signing
                var createdCertificateBundle = await _keyVaultClient.GetCertificateAsync(
                    _vaultBaseUrl, certificateName, ct);

                caTempCertIdentifier =
                    createdCertificateBundle.CertificateIdentifier.Identifier;

                // policy unknown issuer, reuse key - not exportable
                var policyUnknownReuse = CreateCertificatePolicy(
                    subjectName.Name, keyParams, false, _keyStoreIsHsm, true, false);
                var attributes = CreateCertificateAttributes(notBefore, lifetime,
                                                             DateTime.MaxValue);

                // create the CSR
                var createResult = await CreateCertificateAsync(certificateName,
                                                                policyUnknownReuse, attributes, null, ct);

                if (createResult.Csr == null)
                {
                    throw new CryptographicUnexpectedOperationException(
                              "Failed to read CSR from CreateCertificate.");
                }

                // decode the CSR and verify consistency
                var info = createResult.Csr.ToCertificationRequest();

                // (2) - Issue root X509 Certificate with the csr.

                var signedcert = await _factory.CreateCertificateAsync(this,
                                                                       new KeyVaultKeyHandle(createdCertificateBundle), subjectName,
                                                                       info.PublicKey,
                                                                       attributes.NotBefore.Value, attributes.Expires.Value,
                                                                       policies.SignatureType.Value, true, extensions, ct);

                // (3) - Complete certificate creation with merger of X509 Certificate.

                var mergeResult = await _keyVaultClient.MergeCertificateAsync(
                    _vaultBaseUrl, certificateName,
                    new X509Certificate2Collection(signedcert), null, null, ct);

                // (4) - Get merged certificate and key identifier

                var mergedCert = await _keyVaultClient.GetCertificateAsync(
                    mergeResult.CertificateIdentifier.Identifier, ct);

                var cert = CertificateEx.Create(mergedCert.Cer,
                                                new KeyVaultKeyHandle(mergedCert), policies);
                await _certificates.AddCertificateAsync(certificateName, cert,
                                                        mergedCert.CertificateIdentifier.Identifier, ct);

                return(cert);
            }
            catch (KeyVaultErrorException kex) {
                throw new ExternalDependencyException(
                          "Failed to create new Root CA certificate", kex);
            }
            finally {
                if (caTempCertIdentifier != null)
                {
                    // disable the temp cert for self signing operation
                    var attr = new CertificateAttributes {
                        Enabled = false
                    };
                    await Try.Async(() => _keyVaultClient.UpdateCertificateAsync(
                                        caTempCertIdentifier, null, attr));
                }
            }
        }
Beispiel #16
0
        /// <summary>
        /// Creates a new Root CA certificate in group id, tags it for trusted or issuer store.
        /// </summary>
        public async Task <X509Certificate2> CreateCACertificateAsync(
            string id,
            string subject,
            DateTime notBefore,
            DateTime notAfter,
            int keySize,
            int hashSize,
            bool trusted,
            string crlDistributionPoint = null,
            CancellationToken ct        = default)
        {
            try
            {
                // delete pending operations
                await _keyVaultClient.DeleteCertificateOperationAsync(_vaultBaseUrl, id);
            }
            catch
            {
                // intentionally ignore errors
            }

            string caTempCertIdentifier = null;

            try
            {
                // policy self signed, new key
                var policySelfSignedNewKey = CreateCertificatePolicy(subject, keySize, true, false);
                var tempAttributes         = CreateCertificateAttributes(DateTime.UtcNow.AddMinutes(-10), DateTime.UtcNow.AddMinutes(10));
                var createKey = await _keyVaultClient.CreateCertificateAsync(
                    _vaultBaseUrl,
                    id,
                    policySelfSignedNewKey,
                    tempAttributes,
                    null,
                    ct)
                                .ConfigureAwait(false);

                CertificateOperation operation;
                do
                {
                    await Task.Delay(1000);

                    operation = await _keyVaultClient.GetCertificateOperationAsync(_vaultBaseUrl, id, ct);
                } while (operation.Status == "inProgress" && !ct.IsCancellationRequested);
                if (operation.Status != "completed")
                {
                    throw new ServiceResultException(StatusCodes.BadUnexpectedError, "Failed to create new key pair.");
                }
                var createdCertificateBundle = await _keyVaultClient.GetCertificateAsync(_vaultBaseUrl, id).ConfigureAwait(false);

                var caCertKeyIdentifier = createdCertificateBundle.KeyIdentifier.Identifier;
                caTempCertIdentifier = createdCertificateBundle.CertificateIdentifier.Identifier;

                // policy unknown issuer, reuse key
                var policyUnknownReuse = CreateCertificatePolicy(subject, keySize, false, true);
                var attributes         = CreateCertificateAttributes(notBefore, notAfter);
                var tags = CreateCertificateTags(id, trusted);

                // create the CSR
                var createResult = await _keyVaultClient.CreateCertificateAsync(
                    _vaultBaseUrl,
                    id,
                    policyUnknownReuse,
                    attributes,
                    tags,
                    ct)
                                   .ConfigureAwait(false);

                if (createResult.Csr == null)
                {
                    throw new ServiceResultException(StatusCodes.BadInvalidArgument, "Failed to read CSR from CreateCertificate.");
                }

                // decode the CSR and verify consistency
                var pkcs10CertificationRequest = new Org.BouncyCastle.Pkcs.Pkcs10CertificationRequest(createResult.Csr);
                var info = pkcs10CertificationRequest.GetCertificationRequestInfo();
                if (createResult.Csr == null ||
                    pkcs10CertificationRequest == null ||
                    !pkcs10CertificationRequest.Verify())
                {
                    throw new ServiceResultException(StatusCodes.BadInvalidArgument, "Invalid CSR.");
                }

                // create the self signed root CA cert
                var publicKey  = KeyVaultCertFactory.GetRSAPublicKey(info.SubjectPublicKeyInfo);
                var signedcert = await KeyVaultCertFactory.CreateSignedCertificate(
                    null,
                    null,
                    subject,
                    null,
                    (ushort)keySize,
                    notBefore,
                    notAfter,
                    (ushort)hashSize,
                    null,
                    publicKey,
                    new KeyVaultSignatureGenerator(this, caCertKeyIdentifier, null),
                    true,
                    crlDistributionPoint);

                // merge Root CA cert with
                var mergeResult = await _keyVaultClient.MergeCertificateAsync(
                    _vaultBaseUrl,
                    id,
                    new X509Certificate2Collection(signedcert)
                    );

                return(signedcert);
            }
            catch (KeyVaultErrorException kex)
            {
                var ex = kex;
                throw new ServiceResultException(StatusCodes.BadInternalError, "Failed to create new Root CA certificate");
            }
            finally
            {
                if (caTempCertIdentifier != null)
                {
                    try
                    {
                        // disable the temp cert for self signing operation
                        var attr = new CertificateAttributes()
                        {
                            Enabled = false
                        };
                        await _keyVaultClient.UpdateCertificateAsync(caTempCertIdentifier, null, attr);
                    }
                    catch
                    {
                        // intentionally ignore error
                    }
                }
            }
        }
        public void CertificateAttribute_MatchesAny()
        {
            #region Passes

            {
                List <CertificateAttributes> whitelist = new List <CertificateAttributes>
                {
                    new CertificateAttributes
                    {
                        CommonName          = "CommonName",
                        OrganisationalUnits = new List <string> {
                            "OU0", "OU1", "OU2"
                        },
                        Organisation = "Organisation"
                    }
                };

                {
                    var baseCert = new CertificateAttributes
                    {
                        CommonName          = "CommonName",
                        OrganisationalUnits = new List <string>
                        {
                            "OU0",
                            "OU1",
                            "OU2"
                        },
                        Organisation = "Organisation"
                    };

                    Assert.IsTrue(baseCert.MatchesAny(whitelist));
                }
            }

            {
                List <CertificateAttributes> whitelist = new List <CertificateAttributes>
                {
                    new CertificateAttributes
                    {
                        CommonName          = "CommonName",
                        OrganisationalUnits = new List <string> {
                            "OU0"
                        },
                        Organisation = "Organisation"
                    }
                };

                {
                    var baseCert = new CertificateAttributes
                    {
                        CommonName          = "CommonName",
                        OrganisationalUnits = new List <string>
                        {
                            "OU0",
                            "OU1",
                            "OU2"
                        },
                        Organisation = "Organisation"
                    };

                    Assert.IsTrue(baseCert.MatchesAny(whitelist));
                }
            }

            {
                List <CertificateAttributes> whitelist = new List <CertificateAttributes>
                {
                    new CertificateAttributes
                    {
                        CommonName = "CommonName"
                    }
                };

                {
                    var baseCert = new CertificateAttributes
                    {
                        CommonName          = "CommonName",
                        OrganisationalUnits = new List <string>
                        {
                            "OU0",
                            "OU1",
                            "OU2"
                        },
                        Organisation = "Organisation"
                    };

                    Assert.IsTrue(baseCert.MatchesAny(whitelist));
                }
            }

            {
                List <CertificateAttributes> whitelist = new List <CertificateAttributes>
                {
                    new CertificateAttributes
                    {
                        Organisation = "Organisation"
                    }
                };

                {
                    var baseCert = new CertificateAttributes
                    {
                        CommonName          = "CommonName",
                        OrganisationalUnits = new List <string>
                        {
                            "OU0",
                            "OU1",
                            "OU2"
                        },
                        Organisation = "Organisation"
                    };

                    Assert.IsTrue(baseCert.MatchesAny(whitelist));
                }
            }

            #endregion

            #region Failues

            {
                List <CertificateAttributes> whitelist = new List <CertificateAttributes>
                {
                    new CertificateAttributes
                    {
                        CommonName          = "CommonName",
                        OrganisationalUnits = new List <string> {
                            "OU0", "OU1", "OU2"
                        },
                        Organisation = "Organisation"
                    }
                };

                {
                    var baseCert = new CertificateAttributes
                    {
                        CommonName          = "CommonName",
                        OrganisationalUnits = new List <string>
                        {
                            "OU3",
                            "OU4",
                            "OU5"
                        },
                        Organisation = "Organisation"
                    };

                    Assert.IsFalse(baseCert.MatchesAny(whitelist));
                }
            }

            {
                List <CertificateAttributes> whitelist = new List <CertificateAttributes>
                {
                    new CertificateAttributes
                    {
                        CommonName          = "DifferentCommonName",
                        OrganisationalUnits = new List <string> {
                            "OU0", "OU1", "OU2"
                        },
                        Organisation = "Organisation"
                    }
                };

                {
                    var baseCert = new CertificateAttributes
                    {
                        CommonName          = "CommonName",
                        OrganisationalUnits = new List <string>
                        {
                            "OU0",
                            "OU1",
                            "OU2"
                        },
                        Organisation = "Organisation"
                    };

                    Assert.IsFalse(baseCert.MatchesAny(whitelist));
                }
            }

            {
                List <CertificateAttributes> whitelist = new List <CertificateAttributes>
                {
                    new CertificateAttributes
                    {
                        CommonName          = "CommonName",
                        OrganisationalUnits = new List <string> {
                            "OU0", "OU1", "OU2"
                        },
                        Organisation = "DifferentOrgnaisation"
                    }
                };

                {
                    var baseCert = new CertificateAttributes
                    {
                        CommonName          = "CommonName",
                        OrganisationalUnits = new List <string>
                        {
                            "OU0",
                            "OU1",
                            "OU2"
                        },
                        Organisation = "Organisation"
                    };

                    Assert.IsFalse(baseCert.MatchesAny(whitelist));
                }
            }

            #endregion
        }
Beispiel #18
0
 public PSKeyVaultCertificate UpdateCertificate(string vaultName, string certificateName, string certificateVersion, CertificateAttributes certificateAttributes, IDictionary <string, string> tags)
 {
     throw new NotImplementedException();
 }
        public CertificateBundle UpdateCertificate(string vaultName, string certificateName, string certificateVersion, CertificateAttributes certificateAttributes, IDictionary <string, string> tags)
        {
            if (string.IsNullOrEmpty(vaultName))
            {
                throw new ArgumentNullException("vaultName");
            }
            if (string.IsNullOrEmpty(certificateName))
            {
                throw new ArgumentNullException("certificateName");
            }

            var certificateIdentifier = new CertificateIdentifier(this.vaultUriHelper.CreateVaultAddress(vaultName), certificateName, certificateVersion);

            CertificateBundle certificateBundle;

            try
            {
                certificateBundle = this.keyVaultClient.UpdateCertificateAsync(
                    certificateIdentifier.Identifier, null, certificateAttributes, tags).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                throw GetInnerException(ex);
            }

            return(certificateBundle);
        }
        public CertificateBundle UpdateCertificate(string vaultName, string certificateName, string certificateVersion, CertificateAttributes certificateAttributes, IDictionary<string, string> tags)
        {
            if (string.IsNullOrEmpty(vaultName))
                throw new ArgumentNullException("vaultName");
            if (string.IsNullOrEmpty(certificateName))
                throw new ArgumentNullException("certificateName");

            var certificateIdentifier = new CertificateIdentifier(this.vaultUriHelper.CreateVaultAddress(vaultName), certificateName, certificateVersion);

            CertificateBundle certificateBundle;
            try
            {
                certificateBundle = this.keyVaultClient.UpdateCertificateAsync(
                    certificateIdentifier.Identifier, null, certificateAttributes, tags).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                throw GetInnerException(ex);
            }

            return certificateBundle;
        }