示例#1
0
        /// <summary>
        /// Gets the public certificate from the certificate store and the private key from the
        /// specified file.
        /// </summary>
        /// <param name="certificate"></param>
        /// <param name="privateKeyFilePath"></param>
        /// <returns></returns>
        private static KeyPair GetMixedKeyPair(string certificate, string privateKeyFilePath)
        {
            Assert.True(File.Exists(privateKeyFilePath),
                        $"The specified private key PEM file {privateKeyFilePath} was not found. " +
                        "In order to use the private key from the certificate, the private key file must not be specified.");

            KeyPair result = null;

            // The private key has been provided already, no need to try to extract it from the store:
            X509Certificate2 x509Certificate2 =
                CertificateUtils.FindValidCertificates(
                    StoreName.My, StoreLocation.LocalMachine,
                    certificate, new[]
            {
                X509FindType
                .FindBySubjectDistinguishedName,
                X509FindType.FindByThumbprint
            })
                .FirstOrDefault();

            if (x509Certificate2 != null)
            {
                string publicKey  = CertificateUtils.ExportToPem(x509Certificate2, true);
                string privateKey = File.ReadAllText(privateKeyFilePath);

                result = new KeyPair(privateKey, publicKey);
            }
            else
            {
                _msg.InfoFormat("Certificate not found in certificate store.");
            }

            return(result);
        }