To make the connection secure, you MUST (at least):
- make sure you trust the certificate,
- check the host name (if you do not know for sure that this is the only and only certificate that you trust, it is possible).
At these two points, your code does not work:
TrustManager
that you use does not validate the certificate at all (it never throws an exception, while the API expects it to throw a CertificateException
form if the certificate is not trusted).- The verifier of your name always returns
true
.
To fix your code:
- Keep default trust managers or initialize them with their own trust store and default
TrustManagerFactory
. - Keep the default host name verifier.
The name of your question ("invalid host name exception") and your example URL https://xxx.xxx.xx.xx:8443
seem to suggest that you are connecting to an IP address.
Unlike some browsers, Java follows the specification ( RFC 2818 ) quite strictly in this regard:
If a subjectAltName extension of type dNSName is present, it MUST be used as an identifier. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is an existing practice, obsolete and certification authorities are encouraged to use dNSName.
[...]
In some cases, the URI is indicated as an IP address rather than a host name. In this case, the subject name iPAddressAltName must be present in the certificate and must exactly match the IP in the URI.
This means that you cannot simply leave by putting the IP address in the Common Name (CN) of your Subject DN into your server certificate. If you use an IP address, it MUST be in the subjectโs alternate name record. (Starting with Java 7, keytool
has options for creating such certificates.)
You will find more information on which commands to use in this answer .
Speaking of which, using IP addresses can only work in the test environment itself. I donโt think any commercial CA will provide you a certificate based on IP address. I would suggest setting up DNS records (even if they were only in hosts
files in a test environment).
Even if you are not using an IP address, you must make sure that this certificate is valid for the host name that you are trying to contact the server with: if you have entries for the alternate subject name, one of them must match the host name; otherwise, the host name must be in the CN RDN of the subject name of this certificate.