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

前端 未结 8 1986
孤街浪徒
孤街浪徒 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: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 SubjectAlternativeNames(this X509Certificate2 cert)
            {
                var subjectAlternativeName = cert.Extensions.Cast()
                    .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()
                    : 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();
            }
        }
    }
    

提交回复
热议问题