1 package com.maverick.ssl; 2 3 import java.io.File ; 4 import java.io.FileInputStream ; 5 import java.security.KeyStore ; 6 import java.security.cert.CertPath ; 7 import java.security.cert.CertPathValidator ; 8 import java.security.cert.CertPathValidatorResult ; 9 import java.security.cert.CertificateException ; 10 import java.security.cert.CertificateFactory ; 11 import java.security.cert.PKIXCertPathValidatorResult ; 12 import java.security.cert.PKIXParameters ; 13 import java.security.cert.TrustAnchor ; 14 import java.security.cert.X509Certificate ; 15 import java.util.Arrays ; 16 17 import javax.net.ssl.X509TrustManager; 18 19 20 public class SSLTransportTrustManager implements X509TrustManager { 21 22 private KeyStore trustcacerts; 23 24 25 public SSLTransportTrustManager() { 26 String filename = System.getProperty("java.home") + "/lib/security/cacerts".replace('/', File.separatorChar); 27 try { 28 FileInputStream is = new FileInputStream (filename); 29 trustcacerts = KeyStore.getInstance(KeyStore.getDefaultType()); 30 String password = "changeit"; 31 trustcacerts.load(is, password.toCharArray()); 32 33 } catch (Exception e) { 34 35 } 36 } 37 38 public void checkClientTrusted(X509Certificate [] chain, String authType) throws CertificateException { 39 throw new CertificateException ("Client certs are not trusted by the custom SSL trust manager."); 40 } 41 42 public void checkServerTrusted(X509Certificate [] chain, String authType) throws CertificateException { 43 46 if("true".equalsIgnoreCase(System.getProperty("com.maverick.ssl.allowUntrustedCertificates"))) 47 return; 48 49 53 54 if (trustcacerts == null) { 55 throw new CertificateException ("No trust store found!"); 56 } else { 57 try { 58 CertificateFactory certFact = CertificateFactory.getInstance("X.509"); 59 CertPath path = certFact.generateCertPath(Arrays.asList(chain)); 60 PKIXParameters params = new PKIXParameters (trustcacerts); 61 params.setRevocationEnabled(false); 62 CertPathValidator certPathValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); 63 CertPathValidatorResult result = certPathValidator.validate(path, params); 64 PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult ) result; 65 TrustAnchor ta = pkixResult.getTrustAnchor(); 66 X509Certificate cert = ta.getTrustedCert(); 67 return; 68 } catch (Exception e) { 69 } 70 } 71 72 throw new CertificateException ("Certificate chain is not trusted"); 73 } 74 75 public X509Certificate [] getAcceptedIssuers() { 76 return null; 77 } 78 } 79 | Popular Tags |