有一需求需要透過程式匯入憑證至 Windows 憑證管理器中

authentication 變數中含有 Certificate 與 CertificateChain 以及 PrivateKey

var certificate = new X509Certificate2(System.Text.Encoding.ASCII.GetBytes(authentication.Certificate));
RSA privateKey = RSA.Create();
privateKey.ImportFromPem(authentication.PrivateKey.ToCharArray());

var certificateWithKey = certificate.CopyWithPrivateKey(privateKey);
var certCollection = new X509Certificate2Collection(certificateWithKey);

if (!string.IsNullOrEmpty(authentication.CertificateChain))
{
    string[] chainPem = authentication.CertificateChain.Split(new[] { "-----END CERTIFICATE-----" }, StringSplitOptions.RemoveEmptyEntries);

    foreach (var chainCertPem in chainPem)
    {
        if (!string.IsNullOrWhiteSpace(chainCertPem))
        {
            string certPem = chainCertPem.Trim() + "\n-----END CERTIFICATE-----";
            certCollection.Add(new X509Certificate2(System.Text.Encoding.ASCII.GetBytes(certPem)));
        }
    }
}

byte[] pfxBytes = certCollection.Export(X509ContentType.Pfx, "random_password");
X509Certificate2 certificatePfx = new X509Certificate2(pfxBytes, "random_password");

using X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
store.Add(certificatePfx);
store.Close();

var thumbprint = certificatePfx.Thumbprint;

先將憑證合併為 PFX 格式
再透過 X509Store 匯入至憑證管理器中
最後會取得 thumbprint 可做為未來要刪除憑證用的識別碼

分類於:

標籤:

, ,