internal CertificateIdentityItem(CertificateBundle certBundle)
        {
            if (certBundle == null)
            {
                throw new ArgumentNullException("certBundle");
            }
            if (certBundle.Attributes == null)
            {
                throw new ArgumentException(KeyVaultProperties.Resources.InvalidKeyAttributes);
            }

            SetObjectIdentifier(new ObjectIdentifier
            {
                Id        = certBundle.CertificateIdentifier.Identifier,
                Name      = certBundle.CertificateIdentifier.Name,
                VaultName = certBundle.CertificateIdentifier.VaultWithoutScheme,
                Version   = certBundle.CertificateIdentifier.Version
            });

            Enabled   = certBundle.Attributes.Enabled;
            Expires   = certBundle.Attributes.Expires;
            NotBefore = certBundle.Attributes.NotBefore;
            Created   = certBundle.Attributes.Created;
            Updated   = certBundle.Attributes.Updated;
            Tags      = (certBundle.Tags == null) ? null : certBundle.Tags.ConvertToHashtable();
        }
Example #2
0
        protected void GetKeyVaultReady(out Vault vault, out CertificateBundle certificateBundle, out string thumbprint, out string pfxOutputPath, string srcPfxPath = null)
        {
            vault         = TryGetKeyVault(this.KeyVaultResouceGroupName, this.KeyVaultName);
            pfxOutputPath = null;
            if (vault == null)
            {
                WriteVerboseWithTimestamp(string.Format("Creating Azure Key Vault {0}", this.KeyVaultName));
                vault = CreateKeyVault(this.Name, this.KeyVaultName, this.KeyVaultResouceGroupLocation, this.KeyVaultResouceGroupName);
                WriteVerboseWithTimestamp(string.Format("Key Vault is created: {0}", vault.Id));
            }

            this.keyVaultCertificateName = CreateDefaultCertificateName(this.ResourceGroupName);

            if (!string.IsNullOrEmpty(srcPfxPath))
            {
                certificateBundle = ImportCertificateToAzureKeyVault(
                    this.KeyVaultName,
                    this.keyVaultCertificateName,
                    srcPfxPath,
                    GetPfxPassword(srcPfxPath),
                    out thumbprint);
            }
            else
            {
                var vaultUrl = CreateVaultUri(vault.Name);
                CreateSelfSignedCertificate(
                    this.CertificateSubjectName,
                    vaultUrl.ToString(),
                    out thumbprint,
                    out certificateBundle,
                    out pfxOutputPath);
            }
        }
Example #3
0
        private async Task GetCertificateFromKeyVault()
        {
            try
            {
                string clientId       = KeyVaultOptions.Value.ClientId;
                string clientSecret   = KeyVaultOptions.Value.ClientSecret;
                string certificateUrl = KeyVaultOptions.Value.CertificateUrl;

                using KeyVaultClient keyVaultClient = new KeyVaultClient(async(authority, resource, scope) =>
                {
                    ClientCredential adCredential = new ClientCredential(clientId, clientSecret);
                    AuthenticationContext authenticationContext = new AuthenticationContext(authority, null);
                    return((await authenticationContext.AcquireTokenAsync(resource, adCredential)).AccessToken);
                });
                SecretBundle keyVaultCertificatePfx = await keyVaultClient.GetSecretAsync(certificateUrl).ConfigureAwait(false);

                CertificateBundle keyVaultCertificateCer = await keyVaultClient.GetCertificateAsync(certificateUrl.Replace("/secrets/", "/certificates/", StringComparison.OrdinalIgnoreCase)).ConfigureAwait(false);

                DecryptionCertificate   = keyVaultCertificatePfx.Value;
                EncryptionCertificate   = Convert.ToBase64String(keyVaultCertificateCer.Cer);
                EncryptionCertificateId = keyVaultCertificatePfx.SecretIdentifier.Version;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #4
0
        protected override void ProcessRecord()
        {
            if (ShouldProcess(Name, Properties.Resources.ImportCertificate))
            {
                List <CertificateBundle> certBundleList = new List <CertificateBundle>();
                CertificateBundle        certBundle     = null;

                switch (ParameterSetName)
                {
                case ImportCertificateFromFileParameterSet:

                    certBundle = this.DataServiceClient.MergeCertificate(
                        VaultName,
                        Name,
                        LoadCertificateFromFile(),
                        Tag == null ? null : Tag.ConvertToDictionary());

                    break;

                case ImportWithPrivateKeyFromFileParameterSet:

                    X509Certificate2Collection userProvidedCertColl = InitializeCertificateCollection();
                    X509Certificate2Collection certColl             = new X509Certificate2Collection();

                    byte[] base64Bytes;

                    if (Password == null)
                    {
                        base64Bytes = userProvidedCertColl.Export(X509ContentType.Pfx);
                    }
                    else
                    {
                        base64Bytes = userProvidedCertColl.Export(X509ContentType.Pfx, Password.ConvertToString());
                    }

                    string base64CertCollection = Convert.ToBase64String(base64Bytes);
                    certBundle = this.DataServiceClient.ImportCertificate(VaultName, Name, base64CertCollection, Password, Tag == null ? null : Tag.ConvertToDictionary());

                    break;

                case ImportWithPrivateKeyFromCollectionParameterSet:
                    certBundle = this.DataServiceClient.ImportCertificate(VaultName, Name, CertificateCollection, Tag == null ? null : Tag.ConvertToDictionary());

                    break;

                case ImportWithPrivateKeyFromStringParameterSet:
                    certBundle = this.DataServiceClient.ImportCertificate(VaultName, Name, CertificateString, Password, Tag == null ? null : Tag.ConvertToDictionary());

                    break;

                default:
                    throw new ArgumentException(KeyVaultProperties.Resources.BadParameterSetName);
                }

                var certificate = KeyVaultCertificate.FromCertificateBundle(certBundle);
                this.WriteObject(certificate);
            }
        }
        public override void ExecuteCmdlet( )
        {
            if (ShouldProcess(Name, Properties.Resources.RecoverCertificate))
            {
                CertificateBundle certificate = DataServiceClient.RecoverCertificate(VaultName, Name);

                WriteObject(certificate);
            }
        }
        public override async Task <ListViewItemBase> ToggleAsync(CancellationToken cancellationToken)
        {
            CertificateBundle cb = await Session.CurrentVault.UpdateCertificateAsync(Name, null, null, new CertificateAttributes()
            {
                Enabled = !Attributes.Enabled
            }, Tags, cancellationToken);                                                                                                                                                        // Toggle only Enabled attribute

            return(new ListViewItemCertificate(Session, cb));
        }
        internal static PSKeyVaultCertificate FromCertificateBundle(CertificateBundle certificateBundle)
        {
            if (certificateBundle == null)
            {
                return(null);
            }

            return(new PSKeyVaultCertificate(certificateBundle));
        }
        public static async Task <ListViewItemCertificate> NewAsync(ISession session, PropertyObject newObject, CancellationToken cancellationToken)
        {
            PropertyObjectCertificate certNew = (PropertyObjectCertificate)newObject;
            var certCollection = new X509Certificate2Collection();

            certCollection.Add(certNew.Certificate);
            CertificateBundle cb = await session.CurrentVault.ImportCertificateAsync(certNew.Name, certCollection, certNew.CertificatePolicy, certNew.CertificateBundle.Attributes, certNew.ToTagsDictionary(), cancellationToken);

            return(new ListViewItemCertificate(session, cb));
        }
        public override async Task <ListViewItemBase> UpdateAsync(object originalObject, PropertyObject newObject, CancellationToken cancellationToken)
        {
            CertificateBundle         cb      = (CertificateBundle)originalObject;
            PropertyObjectCertificate certNew = (PropertyObjectCertificate)newObject;
            await Session.CurrentVault.UpdateCertificatePolicyAsync(certNew.Name, certNew.CertificatePolicy, cancellationToken);

            cb = await Session.CurrentVault.UpdateCertificateAsync(certNew.Name, null, null, certNew.ToCertificateAttributes(), certNew.ToTagsDictionary(), cancellationToken);

            return(new ListViewItemCertificate(Session, cb));
        }
        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));
        }
        internal PSKeyVaultCertificate(CertificateBundle certificateBundle)
        {
            if (certificateBundle == null)
            {
                throw new ArgumentNullException(nameof(certificateBundle));
            }

            if (certificateBundle.CertificateIdentifier == null)
            {
                throw new ArgumentException(Resources.InvalidKeyIdentifier);
            }

            var vaultUri = new Uri(certificateBundle.CertificateIdentifier.Vault);

            SetObjectIdentifier(new ObjectIdentifier
            {
                Id   = certificateBundle.CertificateIdentifier.Identifier,
                Name = certificateBundle.CertificateIdentifier.Name,
                // VaultName formatted incorrect in certificateBundle
                VaultName = vaultUri.Host.Split('.').First(),
                Version   = certificateBundle.CertificateIdentifier.Version
            });

            if (certificateBundle.Cer != null)
            {
                Certificate = new X509Certificate2(certificateBundle.Cer);
                Thumbprint  = Certificate.Thumbprint;
            }

            if (certificateBundle.KeyIdentifier != null)
            {
                KeyId = certificateBundle.KeyIdentifier.Identifier;
            }

            if (certificateBundle.SecretIdentifier != null)
            {
                SecretId = certificateBundle.SecretIdentifier.Identifier;
            }

            if (certificateBundle.Attributes != null)
            {
                Created       = certificateBundle.Attributes.Created;
                Expires       = certificateBundle.Attributes.Expires;
                NotBefore     = certificateBundle.Attributes.NotBefore;
                Enabled       = certificateBundle.Attributes.Enabled;
                Updated       = certificateBundle.Attributes.Updated;
                RecoveryLevel = certificateBundle.Attributes.RecoveryLevel;
            }

            if (certificateBundle.Tags != null)
            {
                Tags = (Hashtable)certificateBundle.Tags;
            }
        }
Example #12
0
        private async Task <X509Certificate2> ImportCertificateToKeyVaultAsync(KeyVaultClient client, X509Certificate2 certificate)
        {
            CertificateBundle certificateBundle = await client.ImportCertificateAsync(
                _vaultBaseUrl,
                _certificateName,
                new X509Certificate2Collection(certificate),
                new CertificatePolicy(
                    keyProperties : new KeyProperties(false, "RSA", 2048, false),
                    secretProperties : new SecretProperties("application/x-pkcs12")));

            return(new X509Certificate2(certificateBundle.Cer));
        }
Example #13
0
        private X509Certificate2 GetTokenCertificate()
        {
            if (string.IsNullOrEmpty(keyVaultSettings.ClientId) || string.IsNullOrEmpty(keyVaultSettings.ClientSecret))
            {
                return(new X509Certificate2(certSettings.CertificatePath, certSettings.CertificatePwd));
            }

            KeyVaultClient    client      = KeyVaultSettings.GetClient(keyVaultSettings.ClientId, keyVaultSettings.ClientSecret);
            CertificateBundle certificate = client.GetCertificateAsync(keyVaultSettings.SecretUri, certSettings.CertificateName).GetAwaiter().GetResult();
            SecretBundle      secret      = client.GetSecretAsync(certificate.SecretIdentifier.Identifier).GetAwaiter().GetResult();

            byte[] pfxBytes = Convert.FromBase64String(secret.Value);
            return(new X509Certificate2(pfxBytes));
        }
Example #14
0
        public KeyVaultCertificate(CertificateBundle certificateBundle)
        {
            if (certificateBundle == null)
            {
                throw new ArgumentNullException(nameof(certificateBundle));
            }

            if (certificateBundle.Id != null)
            {
                Id   = certificateBundle.CertificateIdentifier.Identifier;
                Name = certificateBundle.CertificateIdentifier.Name;

                // TODO [dragosav] Bring Certificate classes on par with keys/secrets:
                //  - inherit from ObjectIdentifier
                //  - constructors should accept the VaultUriHelper as a parameter
                var vaultUri = new Uri(certificateBundle.CertificateIdentifier.Vault);
                VaultName = vaultUri.Host.Split('.').First( );
            }

            if (certificateBundle.Cer != null)
            {
                Certificate = new X509Certificate2(certificateBundle.Cer);
                Thumbprint  = Certificate.Thumbprint;
            }

            if (certificateBundle.KeyIdentifier != null)
            {
                KeyId = certificateBundle.KeyIdentifier.Identifier;
            }

            if (certificateBundle.SecretIdentifier != null)
            {
                SecretId = certificateBundle.SecretIdentifier.Identifier;
            }

            if (certificateBundle.Attributes != null)
            {
                Created       = certificateBundle.Attributes.Created;
                Enabled       = certificateBundle.Attributes.Enabled;
                Updated       = certificateBundle.Attributes.Updated;
                RecoveryLevel = certificateBundle.Attributes.RecoveryLevel;
            }

            if (certificateBundle.Tags != null)
            {
                Tags = certificateBundle.Tags;
            }
        }
Example #15
0
        public override void ExecuteCmdlet()
        {
            if (InputObject != null)
            {
                VaultName = InputObject.VaultName;
                Name      = InputObject.Name;
            }

            if (ShouldProcess(Name, Properties.Resources.RecoverCertificate))
            {
                WriteWarning("Undo-AzureKeyVaultCertificateRemoval: The output of the cmdlet will be changing from CertificateBundle to PSKeyVaultCertificate in May 2018");
                CertificateBundle certificate = DataServiceClient.RecoverCertificate(VaultName, Name);

                WriteObject(certificate);
            }
        }
Example #16
0
        /// <summary>
        /// Prints out certificate bundle values
        /// </summary>
        /// <param name="certificateBundle"> certificate bundle </param>
        private static void PrintoutCertificate(CertificateBundle certificateBundle)
        {
            Console.Out.WriteLine("\n\tCertificate ID: {0}", certificateBundle.Id);

            var expiryDateStr = certificateBundle.Attributes.Expires.HasValue
                ? certificateBundle.Attributes.Expires.ToString()
                : "Never";

            var notBeforeStr = certificateBundle.Attributes.NotBefore.HasValue
                ? certificateBundle.Attributes.NotBefore.ToString()
                : UnixTimeJsonConverter.EpochDate.ToString();

            Console.Out.WriteLine("Certificate attributes: \n\tIs enabled: {0}\n\tExpiry date: {1}\n\tEnable date: {2}\n\tThumbprint: {3}",
                                  certificateBundle.Attributes.Enabled, expiryDateStr, notBeforeStr, ToHexString(certificateBundle.X5t));

            PrintoutTags(certificateBundle.Tags);
        }
        internal static KeyVaultCertificate FromCertificateBundle(CertificateBundle certificateBundle)
        {
            if (certificateBundle == null)
            {
                return null;
            }

            var kvCertificate = new KeyVaultCertificate();

            if (certificateBundle.Id != null)
            {
                kvCertificate.Id = certificateBundle.CertificateIdentifier.Identifier;
                kvCertificate.Name = certificateBundle.CertificateIdentifier.Name;
            }

            if (certificateBundle.Cer != null)
            {
                kvCertificate.Certificate = new X509Certificate2(certificateBundle.Cer);
                kvCertificate.Thumbprint = kvCertificate.Certificate.Thumbprint;
            }

            if (certificateBundle.KeyIdentifier != null)
            {
                kvCertificate.KeyId = certificateBundle.KeyIdentifier.Identifier;
            }

            if (certificateBundle.SecretIdentifier != null)
            {
                kvCertificate.SecretId = certificateBundle.SecretIdentifier.Identifier;
            }

            if (certificateBundle.Attributes != null)
            {
                kvCertificate.Created = certificateBundle.Attributes.Created;
                kvCertificate.Enabled = certificateBundle.Attributes.Enabled;
                kvCertificate.Updated = certificateBundle.Attributes.Updated;
            }

            if (certificateBundle.Tags != null)
            {
                kvCertificate.Tags = certificateBundle.Tags;
            }

            return kvCertificate;
        }
Example #18
0
        internal static KeyVaultCertificate FromCertificateBundle(CertificateBundle certificateBundle)
        {
            if (certificateBundle == null)
            {
                return(null);
            }

            var kvCertificate = new KeyVaultCertificate();

            if (certificateBundle.Id != null)
            {
                kvCertificate.Id   = certificateBundle.CertificateIdentifier.Identifier;
                kvCertificate.Name = certificateBundle.CertificateIdentifier.Name;
            }

            if (certificateBundle.Cer != null)
            {
                kvCertificate.Certificate = new X509Certificate2(certificateBundle.Cer);
                kvCertificate.Thumbprint  = kvCertificate.Certificate.Thumbprint;
            }

            if (certificateBundle.KeyIdentifier != null)
            {
                kvCertificate.KeyId = certificateBundle.KeyIdentifier.Identifier;
            }

            if (certificateBundle.SecretIdentifier != null)
            {
                kvCertificate.SecretId = certificateBundle.SecretIdentifier.Identifier;
            }

            if (certificateBundle.Attributes != null)
            {
                kvCertificate.Created = certificateBundle.Attributes.Created;
                kvCertificate.Enabled = certificateBundle.Attributes.Enabled;
                kvCertificate.Updated = certificateBundle.Attributes.Updated;
            }

            if (certificateBundle.Tags != null)
            {
                kvCertificate.Tags = certificateBundle.Tags;
            }

            return(kvCertificate);
        }
Example #19
0
        /// <summary>
        /// Exports a certificate as X509Certificate object
        /// </summary>
        /// <param name="certificateBundle"> the certificate bundle </param>
        /// <returns> The exported certificate </returns>
        private static X509Certificate ExportCertificate(CertificateBundle certificateBundle)
        {
            // The contents of a certificate can be obtained by using the secret referenced in the certificate bundle
            var certContentSecret =
                keyVaultClient.GetSecretAsync(certificateBundle.SecretIdentifier.Identifier).GetAwaiter().GetResult();

            // Certificates can be exported in a mutiple formats (PFX, PEM).
            // Use the content type to determine how to strongly-type the certificate for the platform
            // The exported certificate doesn't have a password
            if (0 == string.CompareOrdinal(certContentSecret.ContentType, CertificateContentType.Pfx))
            {
                var exportedCertCollection = new X509Certificate2Collection();
                exportedCertCollection.Import(Convert.FromBase64String(certContentSecret.Value));
                return(exportedCertCollection.Cast <X509Certificate2>().Single(s => s.HasPrivateKey));
            }

            return(null);
        }
        private async Task <List <X509Certificate2> > GetAllCertificateVersions(string keyVaultUrl, string certificateName)
        {
            List <X509Certificate2> certificates = new List <X509Certificate2>();

            KeyVaultClient client = KeyVaultSettings.GetClient(_keyVaultSettings.ClientId, _keyVaultSettings.ClientSecret);

            // Get the first page of certificates
            IPage <CertificateItem> certificateItemsPage = await client.GetCertificateVersionsAsync(keyVaultUrl, certificateName);

            while (true)
            {
                foreach (var certificateItem in certificateItemsPage)
                {
                    // Ignore disabled or expired certificates
                    if (certificateItem.Attributes.Enabled == true &&
                        (certificateItem.Attributes.Expires == null ||
                         certificateItem.Attributes.Expires > DateTime.UtcNow))
                    {
                        CertificateBundle certificateVersionBundle =
                            await client.GetCertificateAsync(certificateItem.Identifier.Identifier);

                        SecretBundle certificatePrivateKeySecretBundle =
                            await client.GetSecretAsync(certificateVersionBundle.SecretIdentifier.Identifier);

                        byte[]           privateKeyBytes           = Convert.FromBase64String(certificatePrivateKeySecretBundle.Value);
                        X509Certificate2 certificateWithPrivateKey = new X509Certificate2(privateKeyBytes);

                        certificates.Add(certificateWithPrivateKey);
                    }
                }

                if (certificateItemsPage.NextPageLink == null)
                {
                    break;
                }

                certificateItemsPage = await client.GetCertificateVersionsNextAsync(certificateItemsPage.NextPageLink);
            }

            return(certificates);
        }
        internal CertificateIdentityItem(CertificateBundle certBundle)
        {
            if (certBundle == null)
                throw new ArgumentNullException("certBundle");
            if (certBundle.Attributes == null)
                throw new ArgumentException(KeyVaultProperties.Resources.InvalidKeyAttributes);

            SetObjectIdentifier(new ObjectIdentifier
            {
                Id = certBundle.CertificateIdentifier.Identifier,
                Name = certBundle.CertificateIdentifier.Name,
                VaultName = certBundle.CertificateIdentifier.VaultWithoutScheme,
                Version = certBundle.CertificateIdentifier.Version
            });

            Enabled = certBundle.Attributes.Enabled;
            Expires = certBundle.Attributes.Expires;
            NotBefore = certBundle.Attributes.NotBefore;
            Created = certBundle.Attributes.Created;
            Updated = certBundle.Attributes.Updated;
            Tags = certBundle.Tags.ConvertToHashtable();
        }
Example #22
0
        /// <summary>
        /// Obtain the <see cref="SigningCredentials"/> to be used when signing a new JSON Web Token.
        /// </summary>
        /// <param name="keyVaultSettings">Settings that can be used to access a key vault with the signing certificate.</param>
        /// <param name="certificateSettings">Settings to identify a certificate stored on the file system.</param>
        /// <returns>The <see cref="SigningCredentials"/>.</returns>
        public static async Task <SigningCredentials> GetSigningCredentials(KeyVaultSettings keyVaultSettings, CertificateSettings certificateSettings)
        {
            await Semaphore.WaitAsync();

            try
            {
                if (_signingCredentialsUpdateTime > DateTime.Now && _signingCredentials != null)
                {
                    return(_signingCredentials);
                }

                X509Certificate2 cert;
                if (string.IsNullOrEmpty(keyVaultSettings.ClientId) || string.IsNullOrEmpty(keyVaultSettings.ClientSecret))
                {
                    cert = new X509Certificate2(certificateSettings.CertificatePath, certificateSettings.CertificatePwd);
                }
                else
                {
                    KeyVaultClient    client      = KeyVaultSettings.GetClient(keyVaultSettings.ClientId, keyVaultSettings.ClientSecret);
                    CertificateBundle certificate = await client.GetCertificateAsync(keyVaultSettings.SecretUri, certificateSettings.CertificateName);

                    SecretBundle secret = await client.GetSecretAsync(certificate.SecretIdentifier.Identifier);

                    byte[] pfxBytes = Convert.FromBase64String(secret.Value);
                    cert = new X509Certificate2(pfxBytes);
                }

                _signingCredentials = new X509SigningCredentials(cert, SecurityAlgorithms.RsaSha256);

                // Reuse the same SigningCredentials for 30 minutes
                _signingCredentialsUpdateTime = DateTime.Now.AddMinutes(30);

                return(_signingCredentials);
            }
            finally
            {
                Semaphore.Release();
            }
        }
        /// <inheritdoc />
        public async Task <List <X509Certificate2> > GetCertificates()
        {
            await _semaphore.WaitAsync();

            try
            {
                if (_certificateUpdateTime > DateTime.Now && _certificates != null)
                {
                    return(_certificates);
                }

                _certificates = new List <X509Certificate2>();

                if (string.IsNullOrEmpty(_keyVaultSettings.ClientId) || string.IsNullOrEmpty(_keyVaultSettings.ClientSecret))
                {
                    _certificates.Add(new X509Certificate2(_certificateSettings.CertificatePath, _certificateSettings.CertificatePwd));
                }
                else
                {
                    KeyVaultClient    client      = KeyVaultSettings.GetClient(_keyVaultSettings.ClientId, _keyVaultSettings.ClientSecret);
                    CertificateBundle certificate = await client.GetCertificateAsync(_keyVaultSettings.SecretUri, _certificateSettings.CertificateName);

                    SecretBundle secret = await client.GetSecretAsync(certificate.SecretIdentifier.Identifier);

                    byte[] pfxBytes = Convert.FromBase64String(secret.Value);
                    _certificates.Add(new X509Certificate2(pfxBytes));
                }

                // Reuse the same list of certificates for 30 minutes.
                _certificateUpdateTime = DateTime.Now.AddMinutes(30);

                return(_certificates);
            }
            finally
            {
                _semaphore.Release();
            }
        }
        public PropertyObjectCertificate(CertificateBundle certificateBundle, CertificatePolicy policy, X509Certificate2 certificate, PropertyChangedEventHandler propertyChanged) :
            base(certificateBundle.CertificateIdentifier, certificateBundle.Tags, certificateBundle.Attributes.Enabled, certificateBundle.Attributes.Expires, certificateBundle.Attributes.NotBefore, propertyChanged)
        {
            CertificateBundle = certificateBundle;
            CertificatePolicy = policy;
            Certificate       = certificate;
            _contentType      = ContentType.Pkcs12;
            _value            = certificate.Thumbprint.ToLowerInvariant();
            var olac = new ObservableLifetimeActionsCollection();

            if (null != CertificatePolicy?.LifetimeActions)
            {
                foreach (var la in CertificatePolicy.LifetimeActions)
                {
                    olac.Add(new LifetimeActionItem()
                    {
                        Type = la.Action.ActionType, DaysBeforeExpiry = la.Trigger.DaysBeforeExpiry, LifetimePercentage = la.Trigger.LifetimePercentage
                    });
                }
            }
            LifetimeActions = olac;
            LifetimeActions.SetPropertyChangedEventHandler(propertyChanged);
        }
        protected override void ProcessRecord()
        {
            CertificateBundle certBundle = null;

            ConfirmAction(
                Force.IsPresent,
                string.Format(
                    CultureInfo.InvariantCulture,
                    KeyVaultProperties.Resources.RemoveCertWarning,
                    Name),
                string.Format(
                    CultureInfo.InvariantCulture,
                    KeyVaultProperties.Resources.RemoveCertWhatIfMessage,
                    Name),
                Name,
                () => { certBundle = this.DataServiceClient.DeleteCertificate(VaultName, Name); });

            if (PassThru.IsPresent)
            {
                var certificate = KeyVaultCertificate.FromCertificateBundle(certBundle);
                this.WriteObject(certificate);
            }
        }
 public GetCertificateResponse(CertificateBundle certificateBundle)
 {
     Name     = certificateBundle.CertificateIdentifier.Name;
     DnsNames = certificateBundle.Policy.X509CertificateProperties.SubjectAlternativeNames.DnsNames;
     Expire   = certificateBundle.Attributes.Expires;
 }
Example #27
0
        internal List <CertificateInformation> GetOrCreateCertificateInformation()
        {
            var certificateInformations = new List <CertificateInformation>();

            if (string.IsNullOrEmpty(this.KeyVaultResouceGroupName))
            {
                this.KeyVaultResouceGroupName = this.ResourceGroupName;
            }

            if (string.IsNullOrEmpty(this.KeyVaultName))
            {
                this.KeyVaultName = CreateDefaultKeyVaultName(this.ResourceGroupName);
            }

            if (ParameterSetName != ByExistingKeyVault)
            {
                var resourceGroup = SafeGetResource(
                    () => this.ResourceManagerClient.ResourceGroups.Get(
                        this.KeyVaultResouceGroupName),
                    true);

                if (resourceGroup == null)
                {
                    this.ResourceManagerClient.ResourceGroups.CreateOrUpdate(
                        this.KeyVaultResouceGroupName,
                        new ResourceGroup()
                    {
                        Location = this.KeyVaultResouceGroupLocation
                    });
                }
            }

            switch (ParameterSetName)
            {
            case ByNewPfxAndVaultName:
            case ByDefaultArmTemplate:
            {
                string            thumbprint        = null;
                Vault             vault             = null;
                CertificateBundle certificateBundle = null;
                string            pfxOutputPath     = null;
                string            commonName        = null;
                GetKeyVaultReady(out vault, out certificateBundle, out thumbprint, out pfxOutputPath, out commonName, null);

                certificateInformations.Add(new CertificateInformation()
                    {
                        KeyVault              = vault,
                        Certificate           = certificateBundle.Cer == null ? null : new X509Certificate2(certificateBundle.Cer),
                        SecretUrl             = certificateBundle.SecretIdentifier.Identifier,
                        CertificateUrl        = certificateBundle.CertificateIdentifier.Identifier,
                        CertificateName       = certificateBundle.CertificateIdentifier.Name,
                        CertificateThumbprint = thumbprint,
                        SecretName            = certificateBundle.SecretIdentifier.Name,
                        Version = certificateBundle.SecretIdentifier.Version,
                        CertificateOutputPath = pfxOutputPath
                    });

                return(certificateInformations);
            }

            case ByExistingPfxAndVaultName:
            {
                var sourcePfxPath = GetPfxSrcFiles();
                foreach (var srcPfx in sourcePfxPath)
                {
                    Vault             vault             = null;
                    CertificateBundle certificateBundle = null;
                    string            thumbprint        = null;
                    string            pfxOutputPath     = null;
                    string            commonName        = null;
                    GetKeyVaultReady(out vault, out certificateBundle, out thumbprint, out pfxOutputPath, out commonName, srcPfx);

                    certificateInformations.Add(new CertificateInformation()
                        {
                            KeyVault    = vault,
                            Certificate =
                                certificateBundle.Cer == null
                                        ? null
                                        : new X509Certificate2(certificateBundle.Cer),
                            CertificateUrl        = certificateBundle.CertificateIdentifier.Identifier,
                            CertificateName       = certificateBundle.CertificateIdentifier.Name,
                            SecretUrl             = certificateBundle.SecretIdentifier.Identifier,
                            CertificateThumbprint = thumbprint,
                            CertificateCommonName = commonName,
                            SecretName            = certificateBundle.SecretIdentifier.Name,
                            Version = certificateBundle.SecretIdentifier.Version
                        });
                }

                return(certificateInformations);
            }

            case ByExistingKeyVault:
            {
                var vault = TryGetKeyVault(this.SecretIdentifier);

                string vaultSecretName;
                string version;
                ExtractSecretNameFromSecretIdentifier(this.SecretIdentifier, out vaultSecretName, out version);
                certificateInformations.Add(new CertificateInformation()
                    {
                        KeyVault              = vault,
                        SecretUrl             = this.SecretIdentifier,
                        CertificateThumbprint = GetThumbprintFromSecret(this.SecretIdentifier),
                        CertificateCommonName = GetCommonNameFromSecret(this.SecretIdentifier),
                        SecretName            = vaultSecretName,
                        Version = version
                    });

                return(certificateInformations);
            }

            default:
                throw new PSArgumentException("Invalid ParameterSetName");
            }
        }
Example #28
0
        public async Task ImportCertificateWithKeyTestAsync()
        {
            using (var mock = Setup((v, q) => {
                var expected = "SELECT TOP 1 * FROM Certificates c " +
                               "WHERE c.Type = 'Certificate' " +
                               "AND c.CertificateName = 'rootca' " +
                               "ORDER BY c.Version DESC";
                if (q == expected)
                {
                    return(v
                           .Where(o => o.Value["Type"] == "Certificate")
                           .Where(o => o.Value["CertificateName"] == "rootca")
                           .OrderByDescending(o => o.Value["Version"]));
                }
                throw new AssertActualExpectedException(expected, q, "Query");
            }, out var service, out var client)) {
                ICertificateStore store = mock.Create <CertificateDatabase>();

                var now  = DateTime.UtcNow;
                var rkey = SignatureType.RS256.CreateCsr("CN=me", true, out var request);
                var cert = request.CreateSelfSigned(now, now + TimeSpan.FromDays(5));

                client.Setup(o => o.ImportCertificateWithHttpMessagesAsync(
                                 It.Is <string>(a => a == kTestVaultUri),
                                 It.Is <string>(a => a == "rootca"),
                                 It.IsNotNull <string>(),
                                 It.IsNotNull <string>(),
                                 It.Is <CertificatePolicy>(p => !p.KeyProperties.Exportable.Value),
                                 It.IsNotNull <CertificateAttributes>(),
                                 It.Is <IDictionary <string, string> >(d => d == null),
                                 It.IsAny <Dictionary <string, List <string> > >(),
                                 It.IsAny <CancellationToken>())).Returns(() => {
                    var result = new CertificateBundle(
                        kTestVaultUri + "/certificates/rootca",
                        kTestVaultUri + "/keys/kid",
                        null,     // not exportable
                        null, null, cert.ToPfx(rkey.ToKey()),
                        null, null, null);
                    return(Task.FromResult(new AzureOperationResponse <CertificateBundle> {
                        Body = result
                    }));
                });

                // Run
                var rootca = await service.ImportCertificateAsync("rootca",
                                                                  cert.ToCertificate(new IssuerPolicies {
                    SignatureType  = SignatureType.RS256,
                    IssuedLifetime = TimeSpan.FromHours(1)
                }), rkey.ToKey());

                var found = await store.FindLatestCertificateAsync("rootca");

                var export = ((IKeyStore)service).ExportKeyAsync(found.KeyHandle);

                // Assert
                Assert.NotNull(rootca);
                Assert.NotNull(found);
                Assert.NotNull(rootca.IssuerPolicies);
                Assert.NotNull(rootca.KeyHandle);
                await Assert.ThrowsAsync <InvalidOperationException>(() => export);

                Assert.Null(rootca.Revoked);
                Assert.Equal(TimeSpan.FromDays(5), rootca.NotAfterUtc - rootca.NotBeforeUtc);
                Assert.Equal(TimeSpan.FromHours(1), rootca.IssuerPolicies.IssuedLifetime);
                Assert.Equal(SignatureType.RS256, rootca.IssuerPolicies.SignatureType);
                Assert.True(rootca.IsValidChain());
                rootca.Verify(rootca);
                Assert.True(rootca.IsSelfSigned());
                Assert.True(rootca.IsIssuer());
                Assert.True(rootca.SameAs(found));
                Assert.NotNull(rootca.GetIssuerSerialNumberAsString());
                Assert.Equal(rootca.GetSubjectName(), rootca.GetIssuerSubjectName());
                Assert.True(rootca.Subject.SameAs(rootca.Issuer));
                using (var rcert = rootca.ToX509Certificate2()) {
                    Assert.Equal(rcert.GetSerialNumber(), rootca.GetSerialNumberAsBytesLE());
                    Assert.Equal(rcert.SerialNumber, rootca.GetSerialNumberAsString());
                    Assert.Equal(rcert.Thumbprint, rootca.Thumbprint);
                }
                Assert.Equal(rootca.GetSerialNumberAsString(), rootca.GetIssuerSerialNumberAsString());
            }
        }
Example #29
0
        private void CreateSelfSignedCertificate(string subjectName, string keyVaultUrl, out string thumbprint, out CertificateBundle certificateBundle, out string outputFilePath)
        {
            outputFilePath = string.Empty;
            var policy = new CertificatePolicy()
            {
                SecretProperties = new SecretProperties {
                    ContentType = Constants.SecretContentType
                },
                X509CertificateProperties = new X509CertificateProperties()
                {
                    Subject = subjectName,
                    Ekus    = new List <string> {
                        "1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.2"
                    }
                },
                IssuerParameters = new IssuerParameters()
                {
                    Name = Constants.SelfSignedIssuerName
                }
            };

            WriteVerboseWithTimestamp(string.Format("Begin to create self signed certificate {0}", this.keyVaultCertificateName));

            CertificateOperation operation;

            try
            {
                operation = this.KeyVaultClient.CreateCertificateAsync(keyVaultUrl, this.keyVaultCertificateName, policy).Result;
            }
            catch (Exception ex)
            {
                WriteErrorWithTimestamp(ex.ToString());
                throw;
            }

            var retry = 120;// 240 * 5 = 20 minutes

            while (retry-- >= 0 && operation != null && operation.Error == null && operation.Status.Equals("inProgress", StringComparison.OrdinalIgnoreCase))
            {
                operation = this.KeyVaultClient.GetCertificateOperationAsync(keyVaultUrl, this.keyVaultCertificateName).Result;
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(WriteVerboseIntervalInSec));
                WriteVerboseWithTimestamp(string.Format("Creating self signed certificate {0} with status {1}", this.keyVaultCertificateName, operation.Status));
            }

            if (retry < 0)
            {
                throw new PSInvalidOperationException(ServiceFabricProperties.Resources.CreateSelfSignedCertificateTimeout);
            }

            if (operation == null)
            {
                throw new PSInvalidOperationException(ServiceFabricProperties.Resources.NoCertificateOperationReturned);
            }

            if (operation.Error != null)
            {
                throw new PSInvalidOperationException(
                          string.Format(ServiceFabricProperties.Resources.CreateSelfSignedCertificateFailedWithErrorDetail,
                                        operation.Status,
                                        operation.StatusDetails,
                                        operation.Error.Code,
                                        operation.Error.Message));
            }

            if (!operation.Status.Equals("completed", StringComparison.OrdinalIgnoreCase) && operation.Error == null)
            {
                throw new PSInvalidOperationException(
                          string.Format(ServiceFabricProperties.Resources.CreateSelfSignedCertificateFailedWithoutErrorDetail,
                                        operation.Status,
                                        operation.StatusDetails));
            }

            certificateBundle = this.KeyVaultClient.GetCertificateAsync(keyVaultUrl, this.keyVaultCertificateName).Result;
            thumbprint        = BitConverter.ToString(certificateBundle.X509Thumbprint).Replace("-", "");

            WriteVerboseWithTimestamp(string.Format("Self signed certificate created: {0}", certificateBundle.Id));

            if (!string.IsNullOrEmpty(this.CertificateOutputFolder))
            {
                outputFilePath = GeneratePfxName(this.CertificateOutputFolder);
                var secretBundle   = this.KeyVaultClient.GetSecretAsync(keyVaultUrl, this.keyVaultCertificateName).Result;
                var kvSecretBytes  = Convert.FromBase64String(secretBundle.Value);
                var certCollection = new X509Certificate2Collection();
                certCollection.Import(kvSecretBytes, null, X509KeyStorageFlags.Exportable);
                var protectedCertificateBytes = certCollection.Export(X509ContentType.Pkcs12, this.CertificatePassword?.ConvertToString());
                File.WriteAllBytes(outputFilePath, protectedCertificateBytes);
            }
        }
 public ListViewItemCertificate(ISession session, CertificateBundle cb) : this(session, cb.CertificateIdentifier, cb.Attributes, Utils.ByteArrayToHex(cb.X509Thumbprint), cb.Tags)
 {
 }
Example #31
0
        public async Task CreateRSARootAndRSAIssuerTestAsync()
        {
            using (var mock = Setup((v, q) => {
                var expected = "SELECT TOP 1 * FROM Certificates c " +
                               "WHERE c.Type = 'Certificate' " +
                               "AND c.CertificateName = 'footca' " +
                               "ORDER BY c.Version DESC";
                if (q == expected)
                {
                    return(v
                           .Where(o => o.Value["Type"] == "Certificate")
                           .Where(o => o.Value["CertificateName"] == "footca")
                           .OrderByDescending(o => o.Value["Version"]));
                }
                expected = "SELECT TOP 1 * FROM Certificates c " +
                           "WHERE c.Type = 'Certificate' " +
                           "AND c.CertificateName = 'rootca' " +
                           "ORDER BY c.Version DESC";
                if (q == expected)
                {
                    return(v
                           .Where(o => o.Value["Type"] == "Certificate")
                           .Where(o => o.Value["CertificateName"] == "rootca")
                           .OrderByDescending(o => o.Value["Version"]));
                }
                expected = "SELECT TOP 1 * FROM Certificates c " +
                           "WHERE c.Type = 'Certificate' " +
                           "AND c.CertificateId = '" + kTestVaultUri + "/certificates/rootca' " +
                           "ORDER BY c.Version DESC";
                if (q == expected)
                {
                    return(v
                           .Where(o => o.Value["Type"] == "Certificate")
                           .Where(o => o.Value["CertificateName"] == "rootca")
                           .OrderByDescending(o => o.Value["Version"]));
                }
                throw new AssertActualExpectedException(expected, q, "Query");
            }, out var service, out var client)) {
                ICertificateStore      store = mock.Create <CertificateDatabase>();
                ICertificateRepository repo  = mock.Create <CertificateDatabase>();

                var now = DateTime.UtcNow;
                using (var rkey = SignatureType.RS256.CreateCsr("CN=thee", true, out var rootcsr))
                    using (var rootca = rootcsr.CreateSelfSigned(now, now + TimeSpan.FromDays(5)))
                        using (var ikey = SignatureType.RS256.CreateCsr("CN=me", true, out var issuercsr))
                            using (var issuer = issuercsr.Create(rootca, now, now + TimeSpan.FromHours(3),
                                                                 Guid.NewGuid().ToByteArray())) {
                                await repo.AddCertificateAsync("rootca",
                                                               rootca.ToCertificate(new IssuerPolicies {
                                    SignatureType  = SignatureType.RS256,
                                    IssuedLifetime = TimeSpan.FromHours(3)
                                },
                                                                                    KeyVaultKeyHandle.Create(kTestVaultUri + "/keys/rkid", null)),
                                                               kTestVaultUri + "/certificates/rootca");

                                client.Setup(o => o.GetCertificateWithHttpMessagesAsync(
                                                 It.Is <string>(a => a == kTestVaultUri),
                                                 It.Is <string>(a => a == "rootca"),
                                                 It.IsAny <string>(),
                                                 It.IsAny <Dictionary <string, List <string> > >(),
                                                 It.IsAny <CancellationToken>())).Returns(() => {
                                    var result = new CertificateBundle(
                                        kTestVaultUri + "/certificates/rootca",
                                        kTestVaultUri + "/keys/rkid",
                                        null, // not exportable
                                        null, null, rootca.ToPfx(rkey.ToKey()),
                                        null, null, null);
                                    return(Task.FromResult(new AzureOperationResponse <CertificateBundle> {
                                        Body = result
                                    }));
                                });

                                client.Setup(o => o.CreateCertificateWithHttpMessagesAsync(
                                                 It.Is <string>(a => a == kTestVaultUri),
                                                 It.Is <string>(a => a == "footca"),
                                                 It.IsNotNull <CertificatePolicy>(),
                                                 It.IsNotNull <CertificateAttributes>(),
                                                 It.IsAny <IDictionary <string, string> >(),
                                                 It.IsAny <Dictionary <string, List <string> > >(),
                                                 It.IsAny <CancellationToken>())).Returns(() => {
                                    var result = new CertificateOperation {
                                        Status = "InProgress"
                                    };
                                    return(Task.FromResult(new AzureOperationResponse <CertificateOperation> {
                                        Body = result
                                    }));
                                });

                                client.Setup(o => o.GetCertificateOperationWithHttpMessagesAsync(
                                                 It.Is <string>(a => a == kTestVaultUri),
                                                 It.IsAny <string>(),
                                                 It.IsAny <Dictionary <string, List <string> > >(),
                                                 It.IsAny <CancellationToken>())).Returns(() => {
                                    var result = new CertificateOperation {
                                        Csr    = issuercsr.CreateSigningRequest(),
                                        Status = "Completed"
                                    };
                                    return(Task.FromResult(new AzureOperationResponse <CertificateOperation> {
                                        Body = result
                                    }));
                                });

                                client.Setup(o => o.GetCertificateWithHttpMessagesAsync(
                                                 It.Is <string>(a => a == kTestVaultUri),
                                                 It.Is <string>(a => a == "footca"),
                                                 It.IsAny <string>(),
                                                 It.IsAny <Dictionary <string, List <string> > >(),
                                                 It.IsAny <CancellationToken>())).Returns(() => {
                                    var result = new CertificateBundle(
                                        kTestVaultUri + "/certificates/footca",
                                        kTestVaultUri + "/keys/fkid",
                                        null, // not exportable
                                        null, null, issuer.ToPfx(ikey.ToKey()),
                                        null, null, null);
                                    return(Task.FromResult(new AzureOperationResponse <CertificateBundle> {
                                        Body = result
                                    }));
                                });

                                client.Setup(o => o.MergeCertificateWithHttpMessagesAsync(
                                                 It.Is <string>(a => a == kTestVaultUri),
                                                 It.Is <string>(a => a == "footca"),
                                                 It.IsAny <IList <byte[]> >(),
                                                 It.IsAny <CertificateAttributes>(),
                                                 It.IsAny <IDictionary <string, string> >(),
                                                 It.IsAny <Dictionary <string, List <string> > >(),
                                                 It.IsAny <CancellationToken>())).Returns(() => {
                                    var result = new CertificateBundle(
                                        kTestVaultUri + "/certificates/footca",
                                        kTestVaultUri + "/keys/fkid",
                                        null, // not exportable
                                        null, null, issuer.ToPfx(ikey.ToKey()),
                                        null, null, null);
                                    return(Task.FromResult(new AzureOperationResponse <CertificateBundle> {
                                        Body = result
                                    }));
                                });

                                client.Setup(o => o.SignWithHttpMessagesAsync(
                                                 It.Is <string>(a => a == kTestVaultUri),
                                                 // It.Is<string>(a => a == kTestVaultUri + "/keys/rkid"),
                                                 It.IsAny <string>(),
                                                 It.IsAny <string>(),
                                                 It.IsAny <string>(),
                                                 // It.Is<string>(a => a == "RS256"),
                                                 It.IsAny <byte[]>(),
                                                 It.IsAny <Dictionary <string, List <string> > >(),
                                                 It.IsAny <CancellationToken>())).Returns(() => {
                                    var result = new KeyOperationResult(
                                        kTestVaultUri + "/keys/rkid",
                                        new byte[32]);
                                    return(Task.FromResult(new AzureOperationResponse <KeyOperationResult> {
                                        Body = result
                                    }));
                                });


                                // Run
                                var footca = await service.NewIssuerCertificateAsync("rootca", "footca",
                                                                                     X500DistinguishedNameEx.Create("CN=me"), DateTime.UtcNow,
                                                                                     new CreateKeyParams { KeySize = 2048, Type = KeyType.RSA },
                                                                                     new IssuerPolicies { IssuedLifetime = TimeSpan.FromHours(1) });

                                var found = await store.FindLatestCertificateAsync("footca");

                                // Assert
                                Assert.NotNull(footca);
                                Assert.NotNull(found);
                                Assert.NotNull(footca.IssuerPolicies);
                                Assert.NotNull(footca.KeyHandle);
                                Assert.Null(footca.Revoked);
                                Assert.Equal(TimeSpan.FromHours(3), footca.NotAfterUtc - footca.NotBeforeUtc);
                                Assert.Equal(TimeSpan.FromHours(1), footca.IssuerPolicies.IssuedLifetime);
                                Assert.Equal(SignatureType.RS256, footca.IssuerPolicies.SignatureType);
                                Assert.False(footca.IsSelfSigned());
                                Assert.True(footca.IsIssuer());
                                Assert.True(footca.SameAs(found));
                                Assert.Equal(rootca.Subject, footca.GetIssuerSubjectName());
                                Assert.True(rootca.SubjectName.SameAs(footca.Issuer));
                                using (var cert = footca.ToX509Certificate2()) {
                                    Assert.Equal(cert.GetSerialNumber(), footca.GetSerialNumberAsBytesLE());
                                    Assert.Equal(cert.SerialNumber, footca.GetSerialNumberAsString());
                                    Assert.Equal(cert.Thumbprint, footca.Thumbprint);
                                }
                                Assert.True(footca.IsValidChain(rootca.ToCertificate().YieldReturn()));
                            }
            }
        }
Example #32
0
        static void Main(string[] args)
        {
            KeyBundle            keyBundle            = null; // The key specification and attributes
            SecretBundle         secret               = null;
            CertificateBundle    certificateBundle    = null;
            CertificateOperation certificateOperation = null;
            string keyName               = string.Empty;
            string secretName            = string.Empty;
            string certificateName       = string.Empty;
            string certificateCreateName = string.Empty;

            inputValidator = new InputValidator(args);

            ServiceClientTracing.AddTracingInterceptor(new ConsoleTracingInterceptor());
            ServiceClientTracing.IsEnabled = inputValidator.GetTracingEnabled();

            var clientId             = ConfigurationManager.AppSettings["AuthClientId"];
            var cerificateThumbprint = ConfigurationManager.AppSettings["AuthCertThumbprint"];

            var certificate   = FindCertificateByThumbprint(cerificateThumbprint);
            var assertionCert = new ClientAssertionCertificate(clientId, certificate);

            keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(
                                                    (authority, resource, scope) => GetAccessToken(authority, resource, scope, assertionCert)),
                                                new InjectHostHeaderHttpMessageHandler());

            // SECURITY: DO NOT USE IN PRODUCTION CODE; FOR TEST PURPOSES ONLY
            //ServicePointManager.ServerCertificateValidationCallback += ( sender, cert, chain, sslPolicyErrors ) => true;

            List <KeyOperationType> successfulOperations = new List <KeyOperationType>();
            List <KeyOperationType> failedOperations     = new List <KeyOperationType>();

            foreach (var operation in inputValidator.GetKeyOperations())
            {
                try
                {
                    Console.Out.WriteLine("\n\n {0} is in process ...", operation);
                    switch (operation)
                    {
                    case KeyOperationType.CREATE_KEY:
                        keyBundle = CreateKey(keyBundle, out keyName);
                        break;

                    case KeyOperationType.IMPORT_KEY:
                        keyBundle = ImportKey(out keyName);
                        break;

                    case KeyOperationType.GET_KEY:
                        keyBundle = GetKey(keyBundle);
                        break;

                    case KeyOperationType.LIST_KEYVERSIONS:
                        ListKeyVersions(keyName);
                        break;

                    case KeyOperationType.UPDATE_KEY:
                        keyBundle = UpdateKey(keyName);
                        break;

                    case KeyOperationType.DELETE_KEY:
                        DeleteKey(keyName);
                        break;

                    case KeyOperationType.BACKUP_RESTORE:
                        keyBundle = BackupRestoreKey(keyName);
                        break;

                    case KeyOperationType.SIGN_VERIFY:
                        SignVerify(keyBundle);
                        break;

                    case KeyOperationType.ENCRYPT_DECRYPT:
                        EncryptDecrypt(keyBundle);
                        break;

                    case KeyOperationType.ENCRYPT:
                        Encrypt(keyBundle);
                        break;

                    case KeyOperationType.DECRYPT:
                        Decrypt(keyBundle);
                        break;

                    case KeyOperationType.WRAP_UNWRAP:
                        WrapUnwrap(keyBundle);
                        break;

                    case KeyOperationType.CREATE_SECRET:
                        secret = CreateSecret(out secretName);
                        break;

                    case KeyOperationType.GET_SECRET:
                        secret = GetSecret(secret.Id);
                        break;

                    case KeyOperationType.LIST_SECRETS:
                        ListSecrets();
                        break;

                    case KeyOperationType.DELETE_SECRET:
                        secret = DeleteSecret(secretName);
                        break;

                    case KeyOperationType.CREATE_CERTIFICATE:
                        certificateOperation = CreateCertificate(out certificateCreateName);
                        break;

                    case KeyOperationType.IMPORT_CERTIFICATE:
                        certificateBundle = ImportCertificate(out certificateName);
                        break;

                    case KeyOperationType.EXPORT_CERTIFICATE:
                        var x509Certificate = ExportCertificate(certificateBundle);
                        break;

                    case KeyOperationType.LIST_CERTIFICATEVERSIONS:
                        ListCertificateVersions(certificateName);
                        break;

                    case KeyOperationType.LIST_CERTIFICATES:
                        ListCertificates();
                        break;

                    case KeyOperationType.DELETE_CERTIFICATE:
                        certificateBundle = DeleteCertificate(certificateName);
                        certificateBundle = DeleteCertificate(certificateCreateName);
                        break;
                    }
                    successfulOperations.Add(operation);
                }
                catch (KeyVaultErrorException exception)
                {
                    // The Key Vault exceptions are logged but not thrown to avoid blocking execution for other commands running in batch
                    Console.Out.WriteLine("Operation failed: {0}", exception.Body.Error.Message);
                    failedOperations.Add(operation);
                }
            }

            Console.Out.WriteLine("\n\n---------------Successful Key Vault operations:---------------");
            foreach (KeyOperationType type in successfulOperations)
            {
                Console.Out.WriteLine("\t{0}", type);
            }

            if (failedOperations.Count > 0)
            {
                Console.Out.WriteLine("\n\n---------------Failed Key Vault operations:---------------");
                foreach (KeyOperationType type in failedOperations)
                {
                    Console.Out.WriteLine("\t{0}", type);
                }
            }

            Console.Out.WriteLine();
            Console.Out.Write("Press enter to continue . . .");
            Console.In.Read();
        }