javasslcertificatejkssslcontext

SSLConnectionSocketFactory always returns 400(2 way ssl client cert) Certificates were not received


I have an ssl connection(2 way handshake) and I am unable to understand the why the following code procedures 400(openJdk 11, p12 file & password provided by the server , cer file provided by the server) ,

I have created the jks file from the cer file via the following command:

keytool -importcert -file example-api.cer -keystore example-api.jks

The code

    File keyFile = new File(Objects.requireNonNull(exampleController.class.getClassLoader().
            getResource("example-client-api1.p12")).getFile());
    File trustFile = new File(Objects.requireNonNull(exampleController.class.getClassLoader().
            getResource("example-api.jks")).getFile());
    KeyStore keyStore  = KeyStore.getInstance("PKCS12");
    try(FileInputStream inStream = new FileInputStream(keyFile)) {
        keyStore.load(inStream, "password".toCharArray());
    }
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(trustFile, "password".toCharArray() ,new TrustAllStrategy()).
                            loadKeyMaterial(keyStore , "password".toCharArray()).build();
    HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
    SSLConnectionSocketFactory socketFactory =
            new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    CloseableHttpClient httpclient = HttpClients.custom()
            .setSSLHostnameVerifier(hostnameVerifier)
            .setSSLSocketFactory(socketFactory)
            .useSystemProperties()
            .build();
    HttpGet httpget = new HttpGet("https://example-api/link?token=@Secret_Token@");

    System.out.println("executing request" + httpget.getRequestLine());

    return  httpclient.execute(httpget);

The code above always returns 400 (No required SSL certificate was sent).

but the following curl works(on IOS):

curl https://example-api/link?token=@secret_token@ --cacert ./example-api-ca.crt --cert ./example-client-api1.p12:password

Any help would be greatly appreciated


Solution

  • OK So after Some frustrating days: I do not know the reason why but The problem was with the hyphen char ('-') in the hostName of the URL, removing hyphen sign fix the issue , not sure why , but posting it anyway, maybe someone could explain this phenomenon. Example(using the code above):

    example-api -> not working
    example.api -> Works OK