Our application needs a piece of data that it is included in the client cert's common name. Currently, I'm trying to get it from HttpContext.Current.Request.ClientCertificate. How do I read this out? Sadly, I'm trying to code this blind while I figure out why SoapUI isn't sending the cert, so I haven't tried much other than reading about the object on MSDN and poking through the empty properties but I'm not sure what I'm looking for. So to recap, what do I need to do to pull out the common name from this cert? TIA
7 Answers
I am maybe too late to answer your question but i hope this would help others who are looking for the way to get common name from certificate.
If you use 'Subject', you might need to trim away other unnecessary information. For example, CN = localhost,OU = DepartmentName,O = CompanyName,L = Location,S = State,C = Country
Dim store As New X509Store(StoreName.My, StoreLocation.LocalMachine)
store.Open(OpenFlags.ReadOnly)
store.Certificates(0).Subject
But if you use the code below, you will get 'localhost' which directly give you the common name of the certificate.
Dim store As New X509Store(StoreName.My, StoreLocation.LocalMachine)
store.Open(OpenFlags.ReadOnly)
store.Certificates(0).GetNameInfo(X509NameType.SimpleName, False)
Here's the link for reference:- https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.getnameinfo(v=vs.110).aspx
I know a tiny bit about certificates. Here was my workflow:
I started at:
Which lead me to:
HttpClientCertificate (as the return type).
It appears to have a few properties, but none that explicitly are named common name.
Googled: HttpClientCertificate Common Name:
Problem with extracting X509 certificate from Context on web service side
Which had some code:
//extracting Common name from certificate
Subject = cert.Subject.ToString();
Then went to:
which remarks:
If String is specified without a subfield, the HttpClientCertificate collection returns a comma-separated list of subfields. For example, C=US, O= Msft.
And with the extreme limited knowledge I do have, I know the Common Name = is in this list. I have no actual way to test this at the moment, but it shouldn't be hard to parse this value for the name you are looking for.
It's good question (+1), I am happy you asked it as it will probably be useful for future readers.
I created a DotNetFiddle Example and even though it uses HttpWebRequest to get an X509Certificate class, it does have a Subject property that returned the following value for https on www.google.com:
CN=www.google.com, O=Google Inc, L=Mountain View, S=California, C=US
So I'm inclined to believe that Subject on the HttpClientCertificate would be the same values (knowing that CN means CommonName).
-
I appreciate the input. Please don't join the gang of people assuming right off the bat that the OP made no effort to look. I did mention that I wasn't sure what I was looking for. I searched for about 45 minutes and kept getting mixed answers. One of your links is "Problem with extractiving X509 certificate from context on web service side" I did see that link but didn't not follow it because, to be perfectly honest, it doesn't exactly scream "this is what you're looking for". But at the very least, I appreciate your tact in calling me lazy. Commented Sep 4, 2014 at 23:51
-
I was attempting to be humble in all seriousness. The I haven't tried much was subjective so I wasn't sure if it was 5 minutes or 2 hours, etc. I totally understand and my workflow wasn't to put you down in any way, just to explain how I came to the answer. Commented Sep 4, 2014 at 23:54
-
It was the comment at the very end that kinda bugged me but it looks like you edited that out. Thanks :) Commented Sep 5, 2014 at 0:01
-
-
Agreed. I'm hoping to test it once I get a real cert to go through. For some reason, I keep getting an empty object. That's a different issue though. So, based on this, I wrote all the code to snatch that subject and parse it out. Once it's tested, I'll report back and accept the answer. Commented Sep 5, 2014 at 1:06
You may have to adjust due to differences in certificate formats.
Here is some code to do this:
HttpClientCertificate theHttpCertificate = HttpContext.Current.Request.ClientCertificate;
// split the subject into its parts
string[] subjectArray = theHttpCertificate.Subject.Split(',');
string[] nameParts;
string CN = string.Empty;
string firstName = string.Empty;
string lastName = string.Empty;
foreach (string item in subjectArray)
{
string[] oneItem = item.Split('=');
// Split the Subject CN information
if (oneItem[0].Trim() == "CN")
{
CN = oneItem[1];
if (CN.IndexOf(".") > 0)
{// Split the name information
nameParts = CN.Split('.');
lastName = nameParts[0];
firstName = nameParts[1];
}
}
}
Just a oneliner in Linq.
var kvs = cert.Subject.Split(',').Select(x => new KeyValuePair<string, string>(x.Split('=')[0], x.Split('=')[1])).ToList();
Returns a generic list. Dont use dictionary here, because Subject can contain duplicate fields.
-
1I'd Trim() the keys and values to get rid of extra spaces.– PepitoShCommented May 3, 2021 at 16:46
-
2Needs more work if the subject line has a , in a value, such as
CN="Electronic Arts, Inc.", OU=BioWare, O="Electronic Arts, Inc.", L=Redwood City, S=California, C=US
– MgamerzCommented Mar 18, 2022 at 5:30
The best thing to do is to use the build-in GetNameInfo methods using the name type and the boolean flag
Lets assume you use this extension method:
[return:MaybeNull]
public static X509Certificate2? GetCodeSignCertificate(this Assembly asm)
{
if (asm is null)
{
throw new ArgumentNullException(nameof(asm));
}
if (!File.Exists(asm.Location))
{
return null;
}
using var cert=System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromSignedFile(asm.Location);
if (cert is null)
return null;
return new X509Certificate2(cert);
}
You can then use a type in the class to get the certificate like so:
[TestMethod()]
public void TryGetCodeSigning()
{
//var item = new Walter.CallStack();
var item = new List<string>();
using var cert = item.GetType().Assembly.GetCodeSignCertificate();
Assert.IsNotNull(cert.GetNameInfo(X509NameType.SimpleName,true));
}
to get the name of the certificate signing authority
cert.GetNameInfo(X509NameType.SimpleName,true)
to get the name for who the certificate was signed
cert.GetNameInfo(X509NameType.SimpleName,false)
Have a look at X509NameType and look if this works for you.
I created this extension to handle all individual elements of a subject name.
public enum SubjectNameElements {CN,O,L,OU,S,C,}
public static readonly Dictionary<SubjectNameElements, string> SubNameSybms =
new Dictionary<SubjectNameElements, string>{
{ SubjectNameElements.CN,"CN="},
{ SubjectNameElements.O ,"O="},
{ SubjectNameElements.L ,"L="},
{ SubjectNameElements.OU,"OU="},
{ SubjectNameElements.S ,"S="},
{ SubjectNameElements.C ,"C="},
};
/// <summary>
/// Retrieve CN from subject Name of a certificate
/// </summary>
/// <param name="subjName"></param>
/// <param name="symb"></param>
/// <remarks>
/// Example:
/// GetOneElementFromSubjectName("C=IT, S=Italy, L=Torino, O=Example Italy S.p.A., OU=Example-Client, CN=www.google.com",SubjectNameElements.CN) => www.google.com
/// </remarks>
/// <returns> a string value or empty string in case of invalid options </returns>
public static string GetOneElementFromSubjectName(this X500DistinguishedName subjName, SubjectNameElements symb=SubjectNameElements.CN)
{
string subjNameString = subjName.Name;
try
{
string Symb = SubNameSybms[symb];
string CName = subjNameString.Substring(subjNameString.IndexOf(Symb)).Split(",").First().Replace(Symb, string.Empty).Trim();
return CName;
}
catch (Exception ex)
{
Log.Error("Error in GetOneElementFromSubjectName. Ex.Message: '" + ex.Message + "'. Ex.StackTrace: '" + ex.StackTrace + "'");
return string.Empty;
}
}
For .NET 7 and above:
string? commonName = certificate.SubjectName
.EnumerateRelativeDistinguishedNames()
.FirstOrDefault(x => x.GetSingleElementType().FriendlyName == "CN")
?.GetSingleElementValue();