如何在Java中为服务器验证系统编写TLS客户端

时间:2019-06-25 05:38:46

标签: java c# ssl

在我当前的设置中,服务器是用C#编写的,而客户端是用Java编写的。我希望服务器对客户端进行身份验证。我在两端都使用自签名证书。当服务器请求客户端证书时,我希望Java客户端使用自签名证书。我是Java新手,并且已经完成了C#结束。我在C#中使用SSLStream AuthenticateAsServer。在Java中查看SSL套接字,我不知道如何包括证书。

代码的C#部分(服务器):

if (PerformAuthentication)
{
    using (NetworkStream clientNetworkStream = new NetworkStream(clientSocket))
    using (X509Certificate2 serverCertificate = new X509Certificate2(this.serverCertificatePath))
    using (X509Certificate2 clientCert = new X509Certificate2(this.clientPublicCertificatePath))
    {
        serverCertificate.PrivateKey = Pkcs1PemReader.DecodePkcs1PEMFromFile(this.serverPrivateKeyPath);

        // Server side load client certs for validation.
        this.certsValidator = new CertificateValidator(new X509Certificate2[] { clientCert }, serverAuth: false);

        // Performing only the authentication and not encryption. 
        // Setting the leaveInnerStreamOpen to true so that we can use the inner stream for communication after the authentication.
        using (SslStream sslStream = new SslStream(
                                        innerStream: clientNetworkStream, 
                                        leaveInnerStreamOpen: true, 
                                        userCertificateValidationCallback: new RemoteCertificateValidationCallback(this.ValidateRemoteCertificate), 
                                        userCertificateSelectionCallback: null))
        {
            try
            {
                sslStream.AuthenticateAsServer(serverCertificate, true, System.Security.Authentication.SslProtocols.Tls11, true);
            }
            catch (AuthenticationException e)
            {
                Logger.Error(e);
                continue;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

0 个答案:

没有答案