如何在java中禁用客户端的自签名证书?

时间:2016-02-16 06:10:28

标签: java ssl https rest-client webservices-client

我有正版证书" salientrisk.crt"和" salientrisk.key" ,服务器配置为具有这些证书的SSL服务器,现在在客户端,如果我有相同的证书,那么只有它应该能够进行握手,否则它应该失败,它不应该允许客户端与服务器连接。

如何使用公钥/私钥在客户端和服务器之间进行握手。

问题是,如果我在这里通过自签名证书,那么它也是我的工作,我不想要。

我在主类中使用以下代码:

    SSLContext sslContext = null;
                    try{
                        sslContext = SSLContext.getInstance("SSL");
                        ServerTrustManager serverTrustManager = new ServerTrustManager();
                        sslContext.init(null, new TrustManager[]{serverTrustManager}, null);

                    }catch(Exception e){
                        logger.error("Error while getting SSL context", e);
                    }


=================================================


package com.common.restclient;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class ServerTrustManager implements X509TrustManager{

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        // TODO Auto-generated method stub

    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        // TODO Auto-generated method stub
        X509Certificate cert=null;


        try (InputStream inStream = new FileInputStream("SSLCertificate/salientrisk.crt")) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            cert = (X509Certificate)cf.generateCertificate(inStream);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        cert.checkValidity();
        cert.getIssuerUniqueID();
        cert.getSubjectDN();



    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        // TODO Auto-generated method stub
        return null;
    }

}

2 个答案:

答案 0 :(得分:1)

您的服务器中的密钥对可能也是自签名的,而您尝试使用的密钥对可能具有相同的父证书ca

答案 1 :(得分:0)

您正在寻找certificate pinning。查看https://github.com/ikust/hello-pinnedcerts以获取测试代码。