May 20 2008
X509Certificate properties
as part of some WSE implementation, I had a small utility to read the details of a X509 Certificate. especially the SKID (Subject Key Identifier), of the certificate. actually, WSE comes with a certificate reader tool, which reads the SKID of the certificate.
however, i had 2 issues, using this tool:
- i needed to read the properties from a file, which was the X509 certificate, instead of reading it from the certificate stores.
- i also needed a string representation of the certificate to be stored in the database. (i like the idea of a database oriented certificate management)
In order to read the X509Certificate properties, there are 2 namespaces available.
using Microsoft.Web.Services2.Security.X509; using System.Security.Cryptography.X509Certificates;
however, of the 2 namespaces, the Microsoft.Web.Services2.Security.X509 seems to give the Subject Key Identifier of the certificate. it makes all the more sense to use this namespace, when you are working with WSE enabled web services.
the code snippet to read the certificate properties: (certificate is assumed to be in a file location)
using (FileStream stream = new FileStream(certificateFilePath, FileMode.Open)) { byte[] blob = new byte[(int)stream.Length]; stream.Read(blob, 0, (int)stream.Length); using (X509Certificate cert = new X509Certificate(blob)) { this.textBoxBlob.Text = Convert.ToBase64String(blob); this.textBoxSubject.Text = cert.Subject; this.textBoxTokenIssuer.Text = cert.Issuer; this.textBoxSKID.Text = Convert.ToBase64String(cert.GetKeyIdentifier()); this.textBoxExpiry.Text = cert.GetExpirationDateString(); } }
Notes:
- You can get the WSE DLL from here.
- the X509Certificate belongs to the Microsoft.Web.Services2.Security.X509 namespace.
- Convert.ToBase64String(blob) is very useful if you want to store the certificate in a database field. it is one of the ways to eliminate certificate management, for your application.
- The Subject Key Identifier is what uniquely identifies your certificate. when WSE is used in a declarative manner, typically the SKID, Subject and Token Issuer are used in the configuration files.
there’s a solution to every problem; given enough time and money..