简体   繁体   English

Java Rest Client使用自签名证书

[英]Java Rest Client using self-signed Certificate

Hello I'm trying to write a little Rest client which accesses our Cloud server (Rest Webservices). 您好我正在尝试编写一个访问我们的云服务器(Rest Webservices)的Rest客户端。 The connection is secured with a SSL Client Certificate which if I understand correctly is not signedby any Certification Authority, and am having problems. 连接使用SSL客户端证书进行保护,如果我理解正确,则不会由任何证书颁发机构签名,并且遇到问题。

I know that the certificate works fine as I can use this in other programming languages (eg C#, PHP, etc), and also because I am testing the API using Postman, however I cannot really understand how to do this in Java. 我知道证书工作正常,因为我可以在其他编程语言中使用它(例如C#,PHP等),也因为我使用Postman测试API,但是我无法真正理解如何在Java中执行此操作。

I have tried using the P12 certificate file, and I also have .key and .crt files, but still nothing changed. 我已经尝试使用P12证书文件,我也有.key和.crt文件,但仍然没有改变。 The .JKS file I have created using keytool.exe, and I presume it is correct (as far as I could understand). 我使用keytool.exe创建的.JKS文件,我认为它是正确的(据我所知)。

This is the code I am using : 这是我正在使用的代码:

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"));

but every time I launch this I get an error: 但是每次我发布这个都会出错:

"unable to find valid certification path to requested target". “无法找到所请求目标的有效证书路径”。

As far as I could see this is because I don't have a Certification Authority to specify, am I correct? 据我所知,这是因为我没有指定证书颁发机构,我是否正确? Can anyone help me with this? 谁能帮我这个?

Thank you all for your help 谢谢大家的帮助

Tommaso 托马索

/******************* This is how I imported the P12 into the Keystore. / *******************这就是我将P12导入密钥库的方法。 I tried different ways, the last one i tried was: 我尝试了不同的方法,我尝试的最后一个是:

First created the JKS: keytool -genkey -alias myName -keystore c:\\Test\\Certificate\\mykeystoreName.jks 首先创建了JKS: keytool -genkey -alias myName -keystore c:\\ Test \\ Certificate \\ mykeystoreName.jks

then "cleaned up with: keytool -delete -alias myName -keystore c:\\Test\\Certificate\\myKeystoreName.jks 然后“清理: keytool -delete -alias myName -keystore c:\\ Test \\ Certificate \\ myKeystoreName.jks

then imported the P12 file with: keytool -v -importkeystore -srckeystore c:\\Test\\Certificate\\idscertificate.p12 -srcstoretype PKCS12 -destkeystore c:\\Test\\Certificate\\myKeystoreName.jks -deststoretype JKS 然后导入P12文件: keytool -v -importkeystore -srckeystore c:\\ Test \\ Certificate \\ idscertificate.p12 -srcstoretype PKCS12 -destkeystore c:\\ Test \\ Certificate \\ myKeystoreName.jks -deststoretype JKS

Result obtained: Entry for alias idsclientcertificate successfully imported. 获得的结果: 成功导入别名idsclientcertificate的条目。 Import command completed: 1 entries successfully imported, 0 entries failed or cancelled 导入命令已完成:已成功导入1个条目,0个条目失败或已取消

and if I check the content of the keystore I find my imported certificate. 如果我检查密钥库的内容,我会找到我导入的证书。 Nevertheless I still get the same error. 不过我仍然得到同样的错误。

Thank you for your help. 谢谢您的帮助。

/****************************Update February 8th ******************* / **************************** 2月8日更新****************** *

Ok I tried everything, but really everything and now slowly giving up... the situation is the following: 好吧,我尝试了一切,但真的一切,现在慢慢放弃......情况如下:

using the following code so far: 到目前为止使用以下代码:

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);

Unfortunately still not working. 不幸的是仍然没有工作 I tried the following: - include my certificate in the default java cacerts, - specify the alias as my host name, - create a new jks, - load the p12 file, still nothing, same error. 我尝试了以下方法: - 在默认的java cacerts中包含我的证书, - 将别名指定为我的主机名, - 创建一个新的jks, - 加载p12文件,仍然没有,同样的错误。 Error Message I get is: 我得到的错误信息是:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到所请求目标的有效证书路径

If I don't use a certificate, I get another error indicating that the certificate is missing therefore the certificate is loaded (also I see it in my IDE). 如果我不使用证书,我会收到另一个错误,表明证书已丢失,因此证书已加载(我也在IDE中看到它)。

If I use the exact same certificate file from another platform (c# or using a browser) I get the correct response and object (therefore the certificate/password are valid) 如果我使用来自其他平台(c#或使用浏览器)的完全相同的证书文件,我会得到正确的响应和对象(因此证书/密码有效)

Is there any way that I can stop the validation of the certification path? 有什么方法可以阻止认证路径的验证吗?

first of all thank you all for your help. 首先感谢大家的帮助。 I finally got it to work following these steps: 1 - I determined my root CA Cert using command: 我终于按照以下步骤开始工作:1 - 我使用命令确定了我的根CA Cert:

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

then I imported this certificate using Portecle.exe ( https://sourceforge.net/projects/portecle/ ) but you can also import it using the normal keytool command, into my default Java Keystore (jre/lib/security/cacerts) --> Make sure you assign the root URL as Alias (eg *.google.com if you would connect to a google API). 然后我使用Portecle.exe https://sourceforge.net/projects/portecle/导入了此证书,但您也可以使用普通的keytool命令将其导入我的默认Java密钥库(jre / lib / security / cacerts) - - >确保将根URL指定为别名(例如,如果要连接到Google API,则为* .google.com)。 This seems to be very important. 这似乎非常重要。

Then I used the following code: First created the ServerSocketFactory: 然后我使用了以下代码: 首先创建了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;
    }
}

Then I created the connection using: 然后我使用以下方法创建连接:

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();
    }
}

This is what worked for me. 这对我有用。 Thank you all, and also thanks to: this article that guided me on the right direction 谢谢大家,也感谢: 这篇文章引导我走向了正确的方向

Ciao 再见

Instead of using loadKeyMaterial use loadTrustMaterial , the first one is for creating a SSLContext for a server, and the second one is for a client. 而不是使用loadKeyMaterial使用loadTrustMaterial ,第一个用于为服务器创建SSLContext ,第二个用于客户端。

Example: 例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM