Certificate validation Issues when Java accesses HTTPS

Source: Internet
Author: User
Tags ssl connection

In order to avoid security problems as far as possible, many of the company's system services are gradually HTTPS, although the beginning of the process will encounter various problems, but the trend does not change. The most perfect HTTPS application is able to achieve two-way authentication, the client with the private key signature with the server public key encryption, the service side with the private key signature client public key encryption, but in many cases it is impossible for each client to request a certificate, so only the implementation of HTTPS single authentication, that is, as long as the server and certificate, The client only verifies that the HTTPS-side certificate is reliable for HTTPS communication. In some cases, in order not to buy a third-party trust authority to issue certificates, the client in some cases do not do server-side authentication, the two sides only achieve htts encrypted communication. Recently, a problem has been encountered, the HTTPS call certificate validation failed, and ultimately consider or ignore the authentication of the Tuning Service certificate.

The Java program encountered an error while accessing the HTTPS resource Sun.security.validator.ValidatorException:PKIX path building failed: Sun.security.provider.certpath.SunCertPathBuilderException:unable to find valid certification path to requested Target this is essentially a certificate trust issue for Java when it accesses HTTPS resources. How to solve this problem? Why is this problem? Before solving this problem, to understand 1) HTTPS communication process clients have the following steps when communicating with a Web server using HTTPS. (1) The client uses HTTPS URL to access the Web server and requires an SSL connection with the Web server. (2) When a Web server receives a client request, it sends a copy of the Web site's certificate information (the certificate contains the public key) to the client. (3) The client's browser and the Web server begin to negotiate the security level of the SSL connection, which is the level of information encryption. (4) The client's browser establishes the session key according to the security level agreed by both parties, then encrypts the session key using the public key of the website and transmits it to the website. (5) The Web server decrypts the session key using its own private key.  (6) The Web server uses the session key to encrypt communication with the client. 2) certificate trust rules for Java programs as described above, the client gets the certificate information from the server. The caller (client) will have a certificate trust list, and when it gets the certificate information, it will determine whether the certificate can be trusted. If you are using a browser to access the HTTPS resource, found that the certificate is not trusted, usually the box to tell the user, the other party's certificate is not trustworthy, whether continue and so on. The Java Virtual machine does not use the keyring of the operating system directly, but has its own security manager. Similar to the operating system, the security manager of the JDK has a heap of root certificate trusts by default. If your HTTPS site certificate was paid for and trusted by these root certificates, it would be convenient to use Java to access this HTTPS site. Therefore, if you use Java to access an HTTPS resource and find that the certificate is untrusted, you will be quoted the error at the beginning of the article. How to solve the problem1) Import the certificate into the JDK's trust certificate (theoretically feasible, not verified) 2) Add logic on the client (call side), ignore the certificate trust problem the first method, need to be on each machine running the Java program, do import operations, not easy to deploy, therefore, the second method is used. The code corresponding to this method is affixed below. Validate code that works1) Implement the verification method first [Java]View Plain Copy
  1. hostnameverifier HV = new Hostnameverifier () {
  2. Public Boolean verify (String Urlhostname, sslsession session) {
  3. System.out.println ("Warning:url Host:" + urlhostname + "vs. "
  4. + Session.getpeerhost ());
  5. return true;
  6. }
  7. };
  8. private static void Trustallhttpscertificates () throws Exception {
  9. javax.net.ssl.trustmanager[] Trustallcerts = new javax.net.ssl.trustmanager[1];
  10. Javax.net.ssl.TrustManager TM = new MiTM ();
  11. trustallcerts[0] = TM;
  12. Javax.net.ssl.SSLContext sc = Javax.net.ssl.SSLContext
  13. . getinstance ("SSL");
  14. Sc.init (null, trustallcerts, null);
  15. Javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory (SC
  16. . Getsocketfactory ());
  17. }
  18. static class MiTM implements Javax.net.ssl.TrustManager,
  19. Javax.net.ssl.X509TrustManager {
  20. Public java.security.cert.x509certificate[] Getacceptedissuers () {
  21. return null;
  22. }
  23. Public Boolean isservertrusted (
  24. Java.security.cert.x509certificate[] certs) {
  25. return true;
  26. }
  27. Public Boolean isclienttrusted (
  28. Java.security.cert.x509certificate[] certs) {
  29. return true;
  30. }
  31. public void checkservertrusted (
  32. Java.security.cert.x509certificate[] certs, String authtype)
  33. throws Java.security.cert.CertificateException {
  34. return;
  35. }
  36. public void checkclienttrusted (
  37. Java.security.cert.x509certificate[] certs, String authtype)
  38. throws Java.security.cert.CertificateException {
  39. return;
  40. }
  41. }
2) before accessing the HTTPS resource, call the [Java]View Plain Copy
    1. Trustallhttpscertificates ();
    2. Httpsurlconnection.setdefaulthostnameverifier (HV);

http://blog.csdn.net/lizeyang/article/details/18983843

Troubleshoot issues where HTTPS certificate validation does not pass

1. Error message

Java.security.cert.CertificateException:No name matching api.weibo.com found; Nested exception is javax.net.ssl.SSLHandshakeException:java.security.cert.CertificateException:No name matching Api.weibo.com found

Cause: When we call api.weibo.com, we use HTTPS, normally we should use Api.weibo.com's certificate, but for some reason, we can only use our own certificate, which causes the error to be reported when verifying the certificate.

WORKAROUND: Ignore the server side and the client's certificate verification. The related classes that are provided by Java.

2, the concrete realization way

By overriding TrustManager's checkclienttrusted (check client certificate trust) and checkservertrusted (check server-side certificate validation).

and Hostnameverifier's verify (checksum) method to cancel all validation of the certificate.

Import Org.slf4j.logger;import org.slf4j.loggerfactory;import Javax.net.ssl.*;import Java.io.IOException;import Java.net.url;import Java.security.cert.certificateexception;import Java.security.cert.x509certificate;public Final class Disablesslcertificatecheckutil {private static final Logger Logger = Loggerfactory.getlogger (disablesslcer    Tificatecheckutil.class);     /** * Prevent instantiation of utility class.     */Private Disablesslcertificatecheckutil () {}/** * Disable Trust checks for SSL connections.        */public static void Disablechecks () {try {new URL ("https://0.0.0.0/"). GetContent (); } catch (IOException e) {//This invocation would always fail, but it would register the//default S        SL provider to the URL class.            } try {Sslcontext sslc;            SSLC = Sslcontext.getinstance ("TLS"); Trustmanager[] Trustmanagerarray = {new X509trustmanager () {@OverriDe public void checkclienttrusted (x509certificate[] chain, String authtype) throws Certificateexception { } @Override public void checkservertrusted (x509certificate[] chain, String AUT Htype) throws Certificateexception {} @Override public x509certificate[] Get                Acceptedissuers () {return new x509certificate[0];            }            }};            Sslc.init (NULL, trustmanagerarray, NULL);            Httpsurlconnection.setdefaultsslsocketfactory (Sslc.getsocketfactory ()); Httpsurlconnection.setdefaulthostnameverifier (New Hostnameverifier () {@Override public bool                EAN Verify (String s, sslsession sslsession) {return true;        }            });            } catch (Exception e) {logger.error ("error msg:{}", E); throw new IllegalArgumentException ("Certificate Check exception!        "); }    }}

Call Mode:

Disablesslcertificatecheckutil.disablechecks ();

  Scope of Impact : The validation of the certificate will be affected throughout Tomcat. The other items in Tomcat, though, do not execute this piece of code but will also ignore the validation of the certificate.

  Impact Time : All time after the execution of this code takes effect.

Certificate validation Issues when Java accesses HTTPS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.