private static void GetSignatureKey(out RSACryptoServiceProvider rsa, out X509Certificate x509Cert) { rsa = null; x509Cert = null; try { Store st = new Store(); st.Open(CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE, "MY", // Store Name CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED); Certificates selectedCerts = ((ICertificates2)st.Certificates).Select( Messages.DemoTitle, Messages.ChooseCertMessage, false); ICertificate2 selectedCert = ((ICertificate2)selectedCerts[1]); if (selectedCert.HasPrivateKey() == false) { MessageBox.Show(Messages.ChooseCertNoPrivateKey, Messages.ExceptionTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } // This only works with RSA keys if (selectedCert.PublicKey().Algorithm.FriendlyName != "RSA") { MessageBox.Show(Messages.ChooseCertKeyAlgorithm, Messages.ExceptionTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } // Construct the public key CspParameters csp = new CspParameters(); csp.KeyContainerName = selectedCert.PrivateKey.ContainerName; csp.ProviderName = selectedCert.PrivateKey.ProviderName; csp.ProviderType = Convert.ToInt32(selectedCert.PrivateKey.ProviderType); switch (selectedCert.PrivateKey.KeySpec) { case CAPICOM_KEY_SPEC.CAPICOM_KEY_SPEC_KEYEXCHANGE: csp.KeyNumber = 1; break; case CAPICOM_KEY_SPEC.CAPICOM_KEY_SPEC_SIGNATURE: csp.KeyNumber = 2; break; } if (selectedCert.PrivateKey.IsMachineKeyset()) { csp.Flags = CspProviderFlags.UseMachineKeyStore; } rsa = new RSACryptoServiceProvider(csp); x509Cert = GetX509Certificate(selectedCert); } catch (Exception) { MessageBox.Show(Messages.ChooseCertUnableToConstructKey, Messages.ExceptionTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop); } }