HttpsTrusts.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.maxkey.client.utils;
  17. import javax.net.ssl.HostnameVerifier;
  18. import javax.net.ssl.HttpsURLConnection;
  19. import javax.net.ssl.SSLSession;
  20. public class HttpsTrusts {
  21. private static void trustAllHttpsCertificates() throws Exception {
  22. javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
  23. javax.net.ssl.TrustManager tm = new HttpsTrustsTM();
  24. trustAllCerts[0] = tm;
  25. javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
  26. sc.init(null, trustAllCerts, null);
  27. javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  28. }
  29. /*
  30. * https ssl auto trust
  31. */
  32. public static void beforeConnection() {
  33. try {
  34. trustAllHttpsCertificates();
  35. HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
  36. public boolean verify(String urlHostName, SSLSession session) {
  37. System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
  38. return true;
  39. }
  40. });
  41. } catch(Exception e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. static class HttpsTrustsTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager {
  46. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  47. return null;
  48. }
  49. public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
  50. return true;
  51. }
  52. public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
  53. return true;
  54. }
  55. public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
  56. throws java.security.cert.CertificateException {
  57. return;
  58. }
  59. public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
  60. throws java.security.cert.CertificateException {
  61. return;
  62. }
  63. }
  64. }