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
- hostnameverifier HV = new Hostnameverifier () {
- Public Boolean verify (String Urlhostname, sslsession session) {
- System.out.println ("Warning:url Host:" + urlhostname + "vs. "
- + Session.getpeerhost ());
- return true;
- }
- };
- private static void Trustallhttpscertificates () throws Exception {
- javax.net.ssl.trustmanager[] Trustallcerts = new javax.net.ssl.trustmanager[1];
- Javax.net.ssl.TrustManager TM = new MiTM ();
- trustallcerts[0] = TM;
- Javax.net.ssl.SSLContext sc = Javax.net.ssl.SSLContext
- . getinstance ("SSL");
- Sc.init (null, trustallcerts, null);
- Javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory (SC
- . Getsocketfactory ());
- }
- static class MiTM implements Javax.net.ssl.TrustManager,
- Javax.net.ssl.X509TrustManager {
- Public java.security.cert.x509certificate[] Getacceptedissuers () {
- return null;
- }
- Public Boolean isservertrusted (
- Java.security.cert.x509certificate[] certs) {
- return true;
- }
- Public Boolean isclienttrusted (
- Java.security.cert.x509certificate[] certs) {
- return true;
- }
- public void checkservertrusted (
- Java.security.cert.x509certificate[] certs, String authtype)
- throws Java.security.cert.CertificateException {
- return;
- }
- public void checkclienttrusted (
- Java.security.cert.x509certificate[] certs, String authtype)
- throws Java.security.cert.CertificateException {
- return;
- }
- }
2) before accessing the HTTPS resource, call the
[Java]View Plain Copy
- Trustallhttpscertificates ();
- 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