public void RetrieveCertificate() { #region Snippet:RetrieveCertificate KeyVaultCertificateWithPolicy certificateWithPolicy = client.GetCertificate("MyCertificate"); #endregion #region Snippet:GetCertificate KeyVaultCertificate certificate = client.GetCertificateVersion(certificateWithPolicy.Name, certificateWithPolicy.Properties.Version); #endregion }
// // execute GetCertificate // public string Execute(string certificateIdentifierUrl, string filePath = null, string identity = null) { (Uri keyVaultUri, string certificateName, string certificateVersion) = ValidateAndParseCertificateURL(certificateIdentifierUrl); var MIcredential = new ManagedIdentityCredential(identity); var certificateClient = new CertificateClient(keyVaultUri, MIcredential); // Retrieve a certificate (certificate = certificate and private key bundle in Azure terminology) // PEM (Privacy Enhanced Mail) or PFX (Personal Information Exchange; PKCS#12 archive file format) formats // depends on what content type you set in Azure Key Vault at respective certificate. // Both formats usually contain a certificate (possibly with its assorted set of CA certificates) and the corresponding private key // Download CER format (X.509 certificate) // single certificate, alone and without any wrapping (no private key, no password protection, just the certificate) // not supported try { // certificate (and key) is stored as a secret at the end in Azure string secretIdentifierUrl; if (String.IsNullOrEmpty(certificateVersion)) { // certificate has no specific version: // https://my-key-vault.vault.azure.net/certificates/readThisCertificate KeyVaultCertificateWithPolicy certificateWithPolicy = certificateClient.GetCertificate(certificateName); secretIdentifierUrl = certificateWithPolicy.SecretId.ToString(); } else { // certificate has specific version: // https://my-key-vault.vault.azure.net/certificates/readThisCertificate/103a7355c6094bc78307b2db7b85b3c2 KeyVaultCertificate certificate = certificateClient.GetCertificateVersion(certificateName, certificateVersion); secretIdentifierUrl = certificate.SecretId.ToString(); } // filePath: null means get secret into variable only // otherwise secret may be unintentionally saved to file by GetSecret() method string secret = new GetSecret().Execute(secretIdentifierUrl, filePath: null, identity); if (String.IsNullOrEmpty(filePath)) { // print to stdout return(secret); } else { // creates or overwrites file and saves secret into it File.WriteAllText(filePath, secret); return("Saved"); } } catch (Exception ex) { throw AzmiException.IDCheck(identity, ex); } }
// // // **** Cmdlet start **** // // protected override void ProcessRecord() { var cred = new ManagedIdentityCredential(Identity); WriteVerbose($"Parsing certificate... '{Certificate}'"); (Uri keyVault, string certName, string certVersion) = Shared.ParseUrl(Certificate); WriteVerbose($"Obtaining certificate client for '{keyVault}' using '{Identity}'..."); var certificateClient = new CertificateClient(keyVault, cred); KeyVaultCertificate certObj; WriteVerbose($"Obtaining certificate Id {certName}..."); if (String.IsNullOrEmpty(certVersion)) { certObj = certificateClient.GetCertificate(certName); } else { certObj = certificateClient.GetCertificateVersion(certName, certVersion); } var secretId = certObj.SecretId.ToString(); WriteVerbose($"Obtaining certificate from {secretId}..."); // var gs = new GetSecret() { Secret = secretId, Identity = Identity }; // var cert = (string)gs.Invoke(); // currently throws InvalidCastException // Unable to cast object of type '<Invoke>d__40' to type 'System.String'. // string cert = System.Text.Encoding.UTF32.GetString(certObj.Cer); string cert = Convert.ToBase64String(certObj.Cer); // return value if (String.IsNullOrEmpty(File)) { WriteObject(cert); } else { WriteVerbose($"Saving secret to file {File}..."); System.IO.File.WriteAllText(File, cert); // TODO: Add test for file in current dir // TODO: Candidate for async } }
private async Task <TrackKeyExternal> LoadTrackKeyExternalFromKeyVaultAsync(Track track) { var now = DateTimeOffset.UtcNow; var certificateClient = new CertificateClient(new Uri(settings.KeyVault.EndpointUri), tokenCredential); var externalKeys = new List <(string Id, DateTimeOffset?NotBefore)>(); var certificateVersions = certificateClient.GetPropertiesOfCertificateVersionsAsync(track.Key.ExternalName); await foreach (var certificateVersion in certificateVersions) { if (certificateVersion.Enabled == true && certificateVersion.ExpiresOn >= now) { externalKeys.Add((certificateVersion.Version, certificateVersion.NotBefore)); } } if (externalKeys.Count <= 0) { throw new Exception($"Track key external certificate '{track.Key.ExternalName}' do not exist in Key Vault."); } var trackKeyExternal = new TrackKeyExternal(); if (externalKeys.Count == 1) { trackKeyExternal.Keys = new List <TrackKeyExternalItem> { new TrackKeyExternalItem { ExternalId = externalKeys.First().Id } }; } else { var topTwoExternalKeys = externalKeys.OrderByDescending(e => e.NotBefore).Take(2); var firstExternalKey = topTwoExternalKeys.First(); if (firstExternalKey.NotBefore <= now.AddDays(-track.KeyExternalPrimaryAfterDays)) { trackKeyExternal.Keys = new List <TrackKeyExternalItem> { new TrackKeyExternalItem { ExternalId = firstExternalKey.Id }, new TrackKeyExternalItem { ExternalId = topTwoExternalKeys.Last().Id } }; } else { trackKeyExternal.Keys = new List <TrackKeyExternalItem> { new TrackKeyExternalItem { ExternalId = topTwoExternalKeys.Last().Id }, new TrackKeyExternalItem { ExternalId = firstExternalKey.Id } }; } } foreach (var keyItem in trackKeyExternal.Keys) { var certificateWithPolicy = certificateClient.GetCertificateVersion(track.Key.ExternalName, keyItem.ExternalId); var certificateRawValue = certificateWithPolicy?.Value?.Cer; if (certificateRawValue == null) { throw new Exception($"Track key external certificate '{track.Key.ExternalName}' version '{keyItem.ExternalId}' from Key Vault is null."); } keyItem.Key = await new X509Certificate2(certificateRawValue).ToFTJsonWebKeyAsync(); } return(trackKeyExternal); }