Java s2s通过p12证书和基本授权连接到https

Java s2s通过p12证书和基本授权连接到https,java,https,certificate,basic-authentication,p12,Java,Https,Certificate,Basic Authentication,P12,我尝试在Java类上实现,该类将使用p12证书和“基本授权”连接到https服务器。你能概述一下如何结合这两件事,包括安装p12证书吗 已更新。下面是我使用的类: public static void main(String[] args) { try { KeyStore clientStore = KeyStore.getInstance("PKCS12"); clientStore.load(new FileInputStream("d:\\cert

我尝试在Java类上实现,该类将使用p12证书和“基本授权”连接到https服务器。你能概述一下如何结合这两件事,包括安装p12证书吗

已更新。下面是我使用的类:

public static void main(String[] args) {
    try {
        KeyStore clientStore = KeyStore.getInstance("PKCS12");
        clientStore.load(new FileInputStream("d:\\certs\\api\\xx.p12"), "W*53as_G".toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientStore, "W*53as_G".toCharArray());
        KeyManager[] kms = kmf.getKeyManagers();

        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(new FileInputStream("c:\\jdk1.8.0_51\\jre\\lib\\security\\cacerts"), "changeit".toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        TrustManager[] tms = tmf.getTrustManagers();

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(kms, tms, new SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        URL url = new URL("https://apis2s.ee/test");

        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestProperty("Authorization", "Basic " + Base64.encode("andrey:pass_1".getBytes()));
        urlConn.setUseCaches(false);
        urlConn.setAllowUserInteraction(true);
        urlConn.setRequestProperty("Pragma", "no-cache");
        urlConn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        urlConn.setRequestProperty("Content-length", Integer.toString("id=1288210&ip=127.0.0.1".length()));

        StringBuilder builder = new StringBuilder();
        builder.append(urlConn.getResponseCode())
                .append(" ")
                .append(urlConn.getResponseMessage())
                .append("\n");

        System.out.println(builder);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

结果为

SunCertPathBuilderException:找不到请求目标的有效证书路径

并使用SSL调试

%% Invalidated: [Session-1, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]
pool-2-thread-1, SEND TLSv1 ALERT: fatal, description = certificate_unknown
pool-2-thread-1, WRITE: TLSv1 Alert, length = 2
[Raw write]: length = 7
0000: 15 03 01 00 02 02 2E .......
pool-2-thread-1, called closeSocket()
pool-2-thread-1, handling exception: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: 

sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification
我还安装了p12证书和命令 keytool-list-v-keystore c:\jdk1.8.0\u 51\jre\lib\security\cacerts 显示证书信息:



最后,通过请求服务器apis2s.ee团队提供有效的根CA证书,问题得到了解决。在他们发送证书后,我使用命令导入了该证书


keytool-import-alias ca-file d:\certs\api\api\Serv\u ca\u SSL.cer-keystore c:\jdk1.8.0\u 51\jre\lib\security\cacerts-storepass changeit

一切正常(无需重新启动)。我稍微更改了result类以显示服务器输出`

public static void main(String[] args) {
    try {

        KeyStore clientStore = KeyStore.getInstance("PKCS12");
        clientStore.load(new FileInputStream("d:\\certs\\api\\xx.p12"), "W*53as_G".toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientStore, "W*53as_G".toCharArray());
        KeyManager[] kms = kmf.getKeyManagers();

        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(new FileInputStream("c:\\jdk1.8.0_51\\jre\\lib\\security\\cacerts"), "changeit".toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        TrustManager[] tms = tmf.getTrustManagers();

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(kms, tms, new SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        URL url = new URL("https://apis2s.ee/test");

        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestProperty("Authorization", "Basic " + Base64.encode("andrey:pass_1".getBytes()));
        urlConn.setUseCaches(false);
        urlConn.setAllowUserInteraction(true);
        urlConn.setRequestProperty("Pragma", "no-cache");
        urlConn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        urlConn.setRequestProperty("Content-length", Integer.toString("id=1288210&ip=127.0.0.1".length()));

        urlConn.setDoOutput( true );
        urlConn.setRequestProperty( "Content-Length", Integer.toString( jsonParams.length() ));
        PrintStream out = new PrintStream(urlConn.getOutputStream());
        out.print("id=1288210&ip=127.0.0.1");
        out.flush();
        out.close();

        StringBuilder builder = new StringBuilder();
        int responseCode = urlConn.getResponseCode();
        builder.append(responseCode)
                .append(" ")
                .append(urlConn.getResponseMessage())
                .append("\n");

        InputStream res = urlConn.getInputStream();
        Scanner in = new Scanner(res);
        String responseStr = "";
        while(in.hasNextLine()) {
            String s = in.nextLine();
            responseStr+=s;
        }
        System.out.println(builder);
        System.out.println("responseStr: " + responseStr);
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}
`


感谢pedrofb查看代码和建议。

请提供您的代码并说明您有什么问题。现在的问题太广泛了,我在上面添加了我的代码。您需要在cacerts中包含
SSL服务器证书的根CAhttps://apis2s.ee
,而不是私钥。基本授权似乎是okI使用浏览器从导入根CA并将其保存在.cer文件中。然后我导入了itkeytool-import-alias ca-file d:\certs\api\xx.cer-keystore c:\jdk1.8.0\u 51\jre\lib\security\cacerts-storepass changeit,但结果是相同的-异常SunCertPathBuilderException:无法找到请求目标的有效认证路径
public static void main(String[] args) {
    try {

        KeyStore clientStore = KeyStore.getInstance("PKCS12");
        clientStore.load(new FileInputStream("d:\\certs\\api\\xx.p12"), "W*53as_G".toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientStore, "W*53as_G".toCharArray());
        KeyManager[] kms = kmf.getKeyManagers();

        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(new FileInputStream("c:\\jdk1.8.0_51\\jre\\lib\\security\\cacerts"), "changeit".toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        TrustManager[] tms = tmf.getTrustManagers();

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(kms, tms, new SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        URL url = new URL("https://apis2s.ee/test");

        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestProperty("Authorization", "Basic " + Base64.encode("andrey:pass_1".getBytes()));
        urlConn.setUseCaches(false);
        urlConn.setAllowUserInteraction(true);
        urlConn.setRequestProperty("Pragma", "no-cache");
        urlConn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        urlConn.setRequestProperty("Content-length", Integer.toString("id=1288210&ip=127.0.0.1".length()));

        urlConn.setDoOutput( true );
        urlConn.setRequestProperty( "Content-Length", Integer.toString( jsonParams.length() ));
        PrintStream out = new PrintStream(urlConn.getOutputStream());
        out.print("id=1288210&ip=127.0.0.1");
        out.flush();
        out.close();

        StringBuilder builder = new StringBuilder();
        int responseCode = urlConn.getResponseCode();
        builder.append(responseCode)
                .append(" ")
                .append(urlConn.getResponseMessage())
                .append("\n");

        InputStream res = urlConn.getInputStream();
        Scanner in = new Scanner(res);
        String responseStr = "";
        while(in.hasNextLine()) {
            String s = in.nextLine();
            responseStr+=s;
        }
        System.out.println(builder);
        System.out.println("responseStr: " + responseStr);
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}