Using X509Certificate with file and key in c#

浪子不回头ぞ 提交于 2019-12-05 10:22:53

You should use AuthenticateAsClient with a list of certificates:

X509Certificate[] X509Certificates = { certificate };
X509CertificateCollection certsCollection = new X509CertificateCollection(X509Certificates);

sslStream.AuthenticateAsClient(address, certsCollection, SslProtocols.Default, false);

To avoid cert errors: change

  public static bool ValidateCertificate(
   object sender,
   X509Certificate certificate,
   X509Chain chain,
   SslPolicyErrors errors)
   {
        if (errors == SslPolicyErrors.None)
            return true;
        if (certificate != null)
        {
            string SendingCertificateName = "";
            //List<string> Subject = CommaText(certificate.Subject); // decode commalist
            // SendingCertificateName = ExtractNameValue(Subject, "CN"); // get the CN= value
            report = string.Format(CultureInfo.InvariantCulture, "certificatename : {0}, SerialNumber: {1}, {2}, {3}", certificate.Subject, certificate.GetSerialNumberString(), SendingCertificateName, ServerName);
            Console.WriteLine(report);
         }

         Console.WriteLine("Certificate error: {0}", errors);
         int allow = AllowPolicyErrors << 1;  // AllowPolicyErrors property allowing you to pass certain errors
         return (allow & (int)sslPolicyErrors) == (int)sslPolicyErrors;  // or just True if you dont't mind.
    }

This answer may not get you all the way there, but it should get you close.

You were given a Java KeyStore (JKS), containing a private key and corresponding certificate. The password to open the JKS according to your code is "123456".

Because the JKS contains a private key, and from looking at your Java code, it leads me to believe you need a 2-way (mutual) SSL connection. That basically means that you as the client authenticate the server AND the server authenticates you. This JKS file is your credential to use the server.

So how do you use this in C#? First, let's convert the JKS to a PKCS12 keystore with this command:

keytool -importkeystore -srckeystore mySrvKeystore -destkeystore mySrvKeystore.p12 -srcstoretype JKS -deststoretype PKCS12

Now, you can import the PKCS12 file into your Windows keystore, which should make it easily accessible from C#. OR, you can import it into an X509Certificate2 object with this code:

X509Certificate2 cert = X509Certificate2("C:\Path\mySrvKeystore.p12", "123456");

Now, you can use either the Windows keystore or the X509Certificate2 object in C# to establish the SSL connection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!