简体   繁体   中英

Java Rest Client using self-signed Certificate

Hello I'm trying to write a little Rest client which accesses our Cloud server (Rest Webservices). The connection is secured with a SSL Client Certificate which if I understand correctly is not signedby any Certification Authority, and am having problems.

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.

I have tried using the P12 certificate file, and I also have .key and .crt files, but still nothing changed. The .JKS file I have created using keytool.exe, and I presume it is correct (as far as I could understand).

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. I tried different ways, the last one i tried was:

First created the 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

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

Result obtained: Entry for alias idsclientcertificate successfully imported. Import command completed: 1 entries successfully imported, 0 entries failed or cancelled

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 *******************

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. 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

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

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)

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:

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). This seems to be very important.

Then I used the following code: First created the 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.

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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