Is there an easy way to get the Subject Alternate Names from an X509Certificate2 object?
foreach (X509Extension ext in certificate.Extensions)
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();
}
}
}