//**************************************************************** // GetCertPVK // Uses .NET/CAPICOM 2 to search CryptoAPI certificate store. // If filtered cert(s) has private key, get keycontainer name. // If private key is exportable, instantiate .NET RSACSP: // RSACryptoServiceProvider(CspParameters csparm) // Display or export public & private key parameters. // // Copyright (C) 2003. Michel I. Gallant //******************************************* using System; using System.Collections; using System.Security.Cryptography; using CAPICOM; class GetCertPVK { static private String storeName = "MY"; static StoreClass oStore; static Certificates oCerts; static String filter = "JavaScience"; [STAThread] static void Main(string[] args) { oStore = new StoreClass(); try{ oStore.Open( CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE, storeName,CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY | CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_ONLY ); } catch(Exception exc){ Console.WriteLine(exc.Message); return; } oCerts = (Certificates)oStore.Certificates; oCerts = (Certificates)oCerts.Find( CAPICOM_CERTIFICATE_FIND_TYPE.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME,filter, false); Console.WriteLine("\n{0} certificates match substring \"{1}\"", oCerts.Count, filter); string container = null; bool canexp = false; int keyspec = 0; CspParameters cp = null; RSACryptoServiceProvider rsaCSP = null; foreach(Certificate ocert in oCerts){ Console.WriteLine("\n{0}", ocert.SubjectName); if(ocert.HasPrivateKey()){ container = ocert.PrivateKey.ContainerName; canexp = ocert.PrivateKey.IsExportable(); keyspec = (int)ocert.PrivateKey.KeySpec; Console.WriteLine("Key Container: {0}\nType: {1} Exportable: {2}", container, keyspec, canexp) ; if(canexp){ //if pvk is exportable, get .NET RSA and show pvk. cp = new CspParameters(); cp.KeyContainerName = container; cp.KeyNumber = keyspec; rsaCSP = new RSACryptoServiceProvider(cp); //-- display public & private key parameters Console.WriteLine("XML: {0}", rsaCSP.ToXmlString(true)); //-- could also use RSAParameters rsaParams = rsaCSP.ExportParameters(true); cp = null; rsaCSP = null; } } } } }