using System; using System.IO; using System.Text; using System.Security.Cryptography.X509Certificates; public class CertInfo { public static void Main(String[] args) { byte[] certBytes; X509Certificate x509cert; while(true) { Console.WriteLine("\nEnter File Name: "); String filename = Console.ReadLine(); if (filename == "") //exit while(true) loop break; if (!File.Exists(filename)) { Console.WriteLine("File \"{0}\" does not exist!\n", filename); continue; } try{ //try binary DER format first x509cert = X509Certificate.CreateFromCertFile(filename) ; showCertInfo(x509cert); } catch(System.Security.Cryptography.CryptographicException cryptder) { //not binary DER StreamReader sr = File.OpenText(filename); String filestr = sr.ReadToEnd(); sr.Close(); StringBuilder sb = new StringBuilder(filestr) ; sb.Replace("-----BEGIN CERTIFICATE-----", "") ; sb.Replace("-----END CERTIFICATE-----", "") ; //Decode try{ //see if the file is a valid Base64 encoded cert certBytes = Convert.FromBase64String(sb.ToString()) ; x509cert = new X509Certificate(certBytes); showCertInfo(x509cert); } catch(System.FormatException formexc) { Console.WriteLine("Not valid binary DER or Base64 X509 certificate format"); } catch(System.Security.Cryptography.CryptographicException cryptb64) { Console.WriteLine("Not valid binary DER or Base64 X509 certificate format"); } } } // end while true } private static void showCertInfo(X509Certificate x509cert) { Console.WriteLine("Name: " + x509cert.GetName()); Console.WriteLine("Issuer: " + x509cert.GetIssuerName()); Console.WriteLine("Serial Number: " + x509cert.GetSerialNumberString()); Console.WriteLine("Expiration Date: " + x509cert.GetExpirationDateString()); Console.WriteLine("PublicKey: " + x509cert.GetPublicKeyString()); } }