How do you parse the Subject Alternate Names from an X509Certificate2?

前端 未结 8 1972
孤街浪徒
孤街浪徒 2020-12-18 19:40

Is there an easy way to get the Subject Alternate Names from an X509Certificate2 object?

        foreach (X509Extension ext in certificate.Extensions)
               


        
相关标签:
8条回答
  • 2020-12-18 20:41

    Use the Format method of the extension for a printable version.

    X509Certificate2 cert = /* your code here */;
    
    foreach (X509Extension extension in cert.Extensions)
    {
        // Create an AsnEncodedData object using the extensions information.
        AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);
        Console.WriteLine("Extension type: {0}", extension.Oid.FriendlyName);
        Console.WriteLine("Oid value: {0}",asndata.Oid.Value);
        Console.WriteLine("Raw data length: {0} {1}", asndata.RawData.Length, Environment.NewLine);
        Console.WriteLine(asndata.Format(true));
    }
    
    0 讨论(0)
  • 2020-12-18 20:43

    Expanding on Minh Nguyen's Answer taking into account using OID i rewrote it as a extension

    namespace MyExtensions
    {
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Security.Cryptography;
        using System.Security.Cryptography.X509Certificates;
        using System.Text.RegularExpressions;
    
        public static class X509Certificate2Extensions
        {
            private const string SubjectAlternateNameOID = "2.5.29.17";
    
            public static List<string> SubjectAlternativeNames(this X509Certificate2 cert)
            {
                var subjectAlternativeName = cert.Extensions.Cast<X509Extension>()
                    .Where(n => n.Oid.Value == X509Certificate2Extensions.SubjectAlternateNameOID)
                    .Select(n => new AsnEncodedData(n.Oid, n.RawData))
                    .Select(n => n.Format(true))
                    .FirstOrDefault();
    
                return string.IsNullOrWhiteSpace(subjectAlternativeName)
                    ? new List<string>()
                    : subjectAlternativeName.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries)
                        .Select(n => Regex.Match(n, @"^DNS Name=(.+)"))
                        .Where(r => r.Success && !string.IsNullOrWhiteSpace(r.Groups[1].Value))
                        .Select(r => r.Groups[1].Value)
                        .ToList();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题