Certificate hostname verification

600 Views Asked by At

I want to verify the hostname of a given certificate (X509Certificate object). That is, to check whether the hostname matches any of the hostnames listed in the certificate's "Subject Alternative Name" or "Common Name" field.

I read online that you can import javax.net.ssl.HostnameVerifier and then use HttpsURLConnection.getDefaultHostnameVerifier().verify(...) to do that. However, the verify function takes an SSLSession object so it won't work with an X509Certificate object.

I would appreciate your help. Thanks.

1

There are 1 best solutions below

2
On BEST ANSWER

In order to verify that the hostname provided by the server is included in the hostnames included in the certificate's CN or SAN you need to read the hostname from the connection and the SAN & CN from the cert as follows:

   String host = connection.getURL().getHost();

   Collection<List<?>> subjectAlternativeNames = x509.getSubjectAlternativeNames();

   String name = x509.getSubjectX500Principal().getName();
   String cn = name.replace("(?:^|,\\s?)(?:CN=(?<val>\"(?:[^\"]|\"\")+\"|[^,]+)", "$1");

Note that when an SSL connection is established that's exactly what the HostnameVerifier does.