From 1c40c80d93aea3244f78b15ece363f18e266b819 Mon Sep 17 00:00:00 2001 From: Beisi Zhou Date: Tue, 4 Jun 2024 17:27:21 +0800 Subject: [PATCH] align with cli --- .../ImportAzureKeyVaultCertificate.cs | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/KeyVault/KeyVault/Commands/Certificate/ImportAzureKeyVaultCertificate.cs b/src/KeyVault/KeyVault/Commands/Certificate/ImportAzureKeyVaultCertificate.cs index b73c64e5d41c..6d7fa7c86ccc 100644 --- a/src/KeyVault/KeyVault/Commands/Certificate/ImportAzureKeyVaultCertificate.cs +++ b/src/KeyVault/KeyVault/Commands/Certificate/ImportAzureKeyVaultCertificate.cs @@ -18,6 +18,8 @@ using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.WindowsAzure.Commands.Utilities.Common; +using Newtonsoft.Json.Linq; + using System; using System.Collections; using System.Collections.Generic; @@ -25,6 +27,7 @@ using System.Management.Automation; using System.Security; using System.Security.Cryptography.X509Certificates; +using System.Text.RegularExpressions; using KeyVaultProperties = Microsoft.Azure.Commands.KeyVault.Properties; @@ -202,7 +205,7 @@ public override void ExecuteCmdlet() switch (ParameterSetName) { case ImportCertificateFromFileParameterSet: - byte[] base64Bytes = File.ReadAllBytes(FilePath); + byte[] bytes = File.ReadAllBytes(FilePath); bool doImport = false; if (IsPemFile(FilePath)) @@ -227,7 +230,7 @@ public override void ExecuteCmdlet() this.Track2DataClient.ImportCertificate( VaultName, Name, - base64Bytes, + bytes, Password, Tag?.ConvertToDictionary(), IsPemFile(FilePath) ? Constants.PemContentType : Constants.Pkcs12ContentType, @@ -235,7 +238,7 @@ public override void ExecuteCmdlet() this.Track2DataClient.MergeCertificate( VaultName, Name, - new List { base64Bytes }, + GetEnumerableBytes(FilePath), Tag == null ? null : Tag.ConvertToDictionary()); break; @@ -253,6 +256,20 @@ public override void ExecuteCmdlet() this.WriteObject(certBundle); } } + private IEnumerable GetEnumerableBytes(string filePath) + { + var bytesList = new List(); + string texts = File.ReadAllText(filePath); + var pattern = @"-----BEGIN CERTIFICATE-----([^-]+)-----END CERTIFICATE-----"; + Match m = Regex.Match(texts, pattern, RegexOptions.IgnoreCase); + while (m.Success) + { + bytesList.Add(Convert.FromBase64String(m.Groups[1].Value.Replace(Environment.NewLine,""))); + m = m.NextMatch(); + } + + return bytesList; + } private bool IsPemFile(string filePath) {