How to read the SubjectAlternativeName from a PKCS10 request

A while ago I needed to programmatically read the SubjectAlternativeName (DNS) provided in certificate requests, to be able to validate the format of the DNS name.

I tried to do it this way, but unfortunately it didn’t work. Altough it should, by reading the documentation on MSDN.

Here’s the C# code:

string ReadDnsSan(CX509CertificateRequestPkcs10 request)
{
...
foreach (IX509Extension ext in request.X509Extensions)
{
var san = ext as IX509ExtensionAlternativeNames;
// san will always be null
}
...
}

The way I finally managed to solve it, looks like this:

string ReadDnsSan(CX509CertificateRequestPkcs10 request)
{
const string OidSubjectAltName2 = "2.5.29.17";
foreach (IX509Extension ext in request.X509Extensions)
{
if (ext.ObjectId.Value == OidSubjectAltName2)
{
CX509ExtensionAlternativeNames extensionAlternativeNames = new CX509ExtensionAlternativeNames();
extensionAlternativeNames.InitializeDecode(EncodingType.XCN_CRYPT_STRING_BINARY, ext.get_RawData(EncodingType.XCN_CRYPT_STRING_BINARY));
foreach (CAlternativeName alternativeName in extensionAlternativeNames.AlternativeNames)
{
if (alternativeName.Type == AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME)
{
dnsName = alternativeName.strValue;
}
}
}
}
...
}

Finally got some spare time to publish my first post! I hope you enjoy it!