CertToKey: X.509 Certificate To Public Key Converter


CertToKey.exe is a .NET 2 CryptoAPI console application which uses a valid X.509 certificate to create an XML RSAKeyValue string.

CertToKey.exe takes one or two arguments:

    certtokey.exe  <certfile | cert-store name >  [M | m] 
where the first argument can be: If a certificate file is not found in the current directory, an attempt is made to open a certificate store with the same name. The CurrentUser certificate store is searched by default, unless a second argument is specified as "M or "m" in which case only the Machine cert store is searched. If a certificate store is found and can be opened, a certificate select-file dialog is presented. If a valid certificate is found, the certificate is displayed using X509Certificate2UI.DisplayCertificate(X509Certificate2) .

Extracting the Public Key:
An X509Certificate object is created and X509Certificate.GetPublicKey() returns the asn.1 encoded RSA public key. This public key blob is parsed directly. It is possible to use P/Invoke techniques (see references at bottom). However the method used here uses only managed code as implemented in :
     private static String CertToXMLKey(X509Certificate cert)
This function extracts the modulus and exponent, creates an RSACryptoServiceProvider object and initializes it using the modulus and exponent. Finally, the XML b64 encoded public key is exported using RSA.ToXmlString(false) and returned.

The user is then prompted to save the public key data to files. The output key files are named, e.g. for an input search string "devcert1":
         "RSApubkey_devcert1"    "XMLpubkey_devcert1.txt" If the files already exist, no files are saved.

Sample Output

Download CertToKey.exe v1.0.0.0 ( (13,544 bytes .NET Framework 2, Digitally Signed)

C# Source


Other Techniques Using Platform Invoke:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncapi/html/encryptdecrypt2a.asp
How to use certificates to sign and to verify SignedXml objects by using Visual C# .NET


Michel I. Gallant
neutron@istar.ca