【C#】証明書からルート証明書を取得する


■ サンプル

using System;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Forms;

namespace SampleDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://yahoo.co.jp");
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                // Do Nothing
            }

            var certificate = new X509Certificate2(request.ServicePoint.Certificate);

            // ★ここから★
            var chain = new X509Chain();
            int index = 0;
            if (chain.Build(certificate))
            {
                foreach (var chainElement in chain.ChainElements)
                {
                    var chainCertificate = chainElement.Certificate;

                    string fileName = "Certificate" + index + ".cer";
                    File.WriteAllBytes(fileName, chainCertificate.Export(X509ContentType.Cert));

                    index++;
                }
            }
        }
    }
}

関連記事

C#】 OS内の証明書を一覧表示する

https://blogs.yahoo.co.jp/dk521123/36982549.html

C#】レスポンスから証明書を作成する

https://blogs.yahoo.co.jp/dk521123/36987774.html