簡體   English   中英

Java Rest Client使用自簽名證書

[英]Java Rest Client using self-signed Certificate

您好我正在嘗試編寫一個訪問我們的雲服務器(Rest Webservices)的Rest客戶端。 連接使用SSL客戶端證書進行保護,如果我理解正確,則不會由任何證書頒發機構簽名,並且遇到問題。

我知道證書工作正常,因為我可以在其他編程語言中使用它(例如C#,PHP等),也因為我使用Postman測試API,但是我無法真正理解如何在Java中執行此操作。

我已經嘗試使用P12證書文件,我也有.key和.crt文件,但仍然沒有改變。 我使用keytool.exe創建的.JKS文件,我認為它是正確的(據我所知)。

這是我正在使用的代碼:

String keyPassphrase = certPwd;

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream("C:\\Test\\Certificate\\idscertificate.jks"), keyPassphrase.toCharArray());

        SSLContext sslContext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, certPwd.toCharArray())
                .build();

        HttpClient httpClient = HttpClients.custom().setSslcontext(sslContext).build();

        HttpResponse response = httpClient.execute(new HttpGet(
                "https://url_that_I_am_using_to_call_my_rest_web_service"));

但是每次我發布這個都會出錯:

“無法找到所請求目標的有效證書路徑”。

據我所知,這是因為我沒有指定證書頒發機構,我是否正確? 誰能幫我這個?

謝謝大家的幫助

托馬索

/ *******************這就是我將P12導入密鑰庫的方法。 我嘗試了不同的方法,我嘗試的最后一個是:

首先創建了JKS: keytool -genkey -alias myName -keystore c:\\ Test \\ Certificate \\ mykeystoreName.jks

然后“清理: keytool -delete -alias myName -keystore c:\\ Test \\ Certificate \\ myKeystoreName.jks

然后導入P12文件: keytool -v -importkeystore -srckeystore c:\\ Test \\ Certificate \\ idscertificate.p12 -srcstoretype PKCS12 -destkeystore c:\\ Test \\ Certificate \\ myKeystoreName.jks -deststoretype JKS

獲得的結果: 成功導入別名idsclientcertificate的條目。 導入命令已完成:已成功導入1個條目,0個條目失敗或已取消

如果我檢查密鑰庫的內容,我會找到我導入的證書。 不過我仍然得到同樣的錯誤。

謝謝您的幫助。

/ **************************** 2月8日更新****************** *

好吧,我嘗試了一切,但真的一切,現在慢慢放棄......情況如下:

到目前為止使用以下代碼:

SSLContextBuilder sslContext = new SSLContextBuilder();
            sslContext.loadKeyMaterial(readKeyStore(), userPwd.toCharArray());
            //sslContext.loadTrustMaterial(readKeyStore(), new TrustSelfSignedStrategy());

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslContext.build());

            CloseableHttpClient client = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .setSSLHostnameVerifier(new NoopHostnameVerifier())
                    .build();
            HttpGet httpGet = new HttpGet("https://myhost.com/myrest/status");
            httpGet.addHeader("Accept", "application/json;charset=UTF8");
            httpGet.addHeader("Cookie", "sessionids=INeedThis");
            String encoded = Base64.getEncoder().encodeToString((userName+":"+userPwd).getBytes(StandardCharsets.UTF_8));
            httpGet.addHeader("Authorization", "Basic "+encoded);
            httpGet.addHeader("Cache-Control", "no-cache");

            HttpResponse response = client.execute(httpGet);

不幸的是仍然沒有工作 我嘗試了以下方法: - 在默認的java cacerts中包含我的證書, - 將別名指定為我的主機名, - 創建一個新的jks, - 加載p12文件,仍然沒有,同樣的錯誤。 我得到的錯誤信息是:

javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路徑構建失敗:sun.security.provider.certpath.SunCertPathBuilderException:無法找到所請求目標的有效證書路徑

如果我不使用證書,我會收到另一個錯誤,表明證書已丟失,因此證書已加載(我也在IDE中看到它)。

如果我使用來自其他平台(c#或使用瀏覽器)的完全相同的證書文件,我會得到正確的響應和對象(因此證書/密碼有效)

有什么方法可以阻止認證路徑的驗證嗎?

首先感謝大家的幫助。 我終於按照以下步驟開始工作:1 - 我使用命令確定了我的根CA Cert:

openssl s_client -showcerts -connect my.root.url.com:443

然后我使用Portecle.exe https://sourceforge.net/projects/portecle/導入了此證書,但您也可以使用普通的keytool命令將其導入我的默認Java密鑰庫(jre / lib / security / cacerts) - - >確保將根URL指定為別名(例如,如果要連接到Google API,則為* .google.com)。 這似乎非常重要。

然后我使用了以下代碼: 首先創建了ServerSocketFactory:

private static SSLSocketFactory getSocketFactory() 
{
    try 
    {
        SSLContext context = SSLContext.getInstance("TLS");

        // Create a key manager factory for our personal PKCS12 key file
        KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance("SunX509");
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        char[] keyStorePassword = pk12Password.toCharArray(); // --> This is the Password for my P12 Client Certificate
        keyStore.load(new FileInputStream(pk12filePath), keyStorePassword); // --> This is the path to my P12 Client Certificate
        keyMgrFactory.init(keyStore, keyStorePassword);

        // Create a trust manager factory for the trust store that contains certificate chains we need to trust
        // our remote server (I have used the default jre/lib/security/cacerts path and password)
        TrustManagerFactory trustStrFactory = TrustManagerFactory.getInstance("SunX509");
        KeyStore trustStore = KeyStore.getInstance("JKS");
        char[] trustStorePassword = jksTrustStorePassword.toCharArray(); // --> This is the Default password for the Java KEystore ("changeit")           
        trustStore.load(new FileInputStream(trustStorePath), trustStorePassword);
        trustStrFactory.init(trustStore);

        // Make our current SSL context use our customized factories
        context.init(keyMgrFactory.getKeyManagers(), 
                trustStrFactory.getTrustManagers(), null);

        return context.getSocketFactory();
    } 
    catch (Exception e) 
    {
        System.err.println("Failed to create a server socket factory...");
        e.printStackTrace();
        return null;
    }
}

然后我使用以下方法創建連接:

public static void launchApi() 
{
    try 
    {
        //  Uncomment this if your server cert is not signed by a trusted CA              
        HostnameVerifier hv = new HostnameVerifier() 
        {
            public boolean verify(String urlHostname, SSLSession session)
            {
                return true;
            }};

        HttpsURLConnection.setDefaultHostnameVerifier(hv);


        URL url = new URL("https://myRootUrl.com/to/launch/api");

        HttpsURLConnection.setDefaultSSLSocketFactory(getSocketFactory());
        HttpsURLConnection urlConn = (HttpsURLConnection)url.openConnection();

        String encoded = Base64.getEncoder().encodeToString((userName+":"+userPwd).getBytes(StandardCharsets.UTF_8));  //Acc User Credentials if needed to log in
        urlConn.setRequestProperty ("Authorization", "Basic "+encoded);
        urlConn.setRequestMethod("GET"); // Specify all needed Request Properties:
        urlConn.setRequestProperty("Accept", "application/json;charset=UTF8");
        urlConn.setRequestProperty("Cache-Control", "no-cache");

        urlConn.connect();

        /* Dump what we have found */
        BufferedReader in = 
            new BufferedReader(
                    new InputStreamReader(urlConn.getInputStream()));
        String inputLine = null;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

這對我有用。 謝謝大家,也感謝: 這篇文章引導我走向了正確的方向

再見

而不是使用loadKeyMaterial使用loadTrustMaterial ,第一個用於為服務器創建SSLContext ,第二個用於客戶端。

例:

SSLContext sslContext = SSLContexts.custom()
                               .loadTrustMaterial(keyStore, new TrustSelfSignedStrategy())
                               .build();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM