sriram
sriram

Reputation: 9042

Check whether the certificate is valid or not

I have the java code like this :

        URL url = new URL(endPoint);
        String encoding = Base64.encodeBase64String(this.key.getBytes());

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);

which is opening a ssl connection. Lets say the endPoint does uses a self-singed certificate and act as a original website. Is it possible to prevent these sort of things in the java code?

Thanks in advance.

Upvotes: 0

Views: 330

Answers (1)

jarnbjo
jarnbjo

Reputation: 34323

By default, the SSL implementation in Java checks against a list of trusted certification authorities, which is included in the Java VM. Unless you extend the default trust store, specify a different trust store at run time or provide your own implementation of a TrustManager and/or HostnameVerifier, you will not be able to make an SSL connection to a server with a self-signed certificate.

If you for some reason need access to the server certificates after you have established the connection, you can get these from an HttpsURLConnection like this:

URL url = new URL("https://www.google.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.connect();

for(Certificate crt : conn.getServerCertificates()) {
    System.out.println(crt);
}

Upvotes: 2

Related Questions