Example usage for java.security.cert CertificateException CertificateException

List of usage examples for java.security.cert CertificateException CertificateException

Introduction

In this page you can find the example usage for java.security.cert CertificateException CertificateException.

Prototype

public CertificateException(Throwable cause) 

Source Link

Document

Creates a CertificateException with the specified cause and a detail message of (cause==null ?

Usage

From source file:org.midonet.api.auth.vsphere.FingerprintTrustManager.java

@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    Preconditions.checkArgument(chain != null && chain.length > 0);
    Preconditions.checkArgument(!StringUtils.isEmpty(authType));

    MessageDigest messageDigest;/*from  w  ww .java2s  .c  om*/
    try {
        messageDigest = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException(e);
    }

    for (X509Certificate certificate : chain) {
        final byte[] rawCertificateFingerprint = messageDigest.digest(certificate.getEncoded());

        final List<String> hexCertificateFingerprint = new ArrayList<>();

        for (byte aByte : rawCertificateFingerprint) {
            hexCertificateFingerprint.add(String.format("%02X", aByte));
        }

        final String fullCertificateFingerprint = Joiner.on(":").join(hexCertificateFingerprint);

        log.debug(String.format("Checking fingerprint %s for certificate %s", fullCertificateFingerprint,
                certificate.getSubjectDN()));

        if (trustedFingerprint.equalsIgnoreCase(fullCertificateFingerprint)) {
            log.debug(String.format("Found a the trusted fingerprint %s " + "for certificate %s",
                    fullCertificateFingerprint, certificate.getSubjectDN()));
            return;
        }
    }

    throw new CertificateException("No trusted certificate found");
}

From source file:test.unit.be.fedict.eid.idp.protocol.openid.OpenIDTrustManager.java

public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    LOG.debug("check server trusted");
    LOG.debug("auth type: " + authType);
    if (null == this.serverCertificate) {
        LOG.debug("trusting all server certificates");
        return;//from w w w. jav a2s.  c om
    }
    if (false == this.serverCertificate.equals(chain[0])) {
        throw new CertificateException("untrusted server certificate");
    }
}

From source file:com.example.bbbbbb.http.sample.util.SecureSocketFactory.java

/**
 * Instantiate a new secured factory pertaining to the passed store. Be sure to initialize the
 * store with the password using {@link KeyStore#load(InputStream,
 * char[])} method./*from w  ww .  j  a v  a2s .c  o  m*/
 *
 * @param store The key store holding the certificate details
 * @param alias The alias of the certificate to use
 */
public SecureSocketFactory(KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException,
        KeyManagementException, KeyStoreException, UnrecoverableKeyException {

    super(store);

    // Loading the CA certificate from store.
    final Certificate rootca = store.getCertificate(alias);

    // Turn it to X509 format.
    InputStream is = new ByteArrayInputStream(rootca.getEncoded());
    X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
    AsyncHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Embedded SSL certificate has expired.");
    }

    // Check the CA's validity.
    x509ca.checkValidity();

    // Accepted CA is only the one installed in the store.
    acceptedIssuers = new X509Certificate[] { x509ca };

    sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            Exception error = null;

            if (null == chain || 0 == chain.length) {
                error = new CertificateException("Certificate chain is invalid.");
            } else if (null == authType || 0 == authType.length()) {
                error = new CertificateException("Authentication type is invalid.");
            } else {
                Log.i(LOG_TAG, "Chain includes " + chain.length + " certificates.");
                try {
                    for (X509Certificate cert : chain) {
                        Log.i(LOG_TAG, "Server Certificate Details:");
                        Log.i(LOG_TAG, "---------------------------");
                        Log.i(LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                        Log.i(LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                        Log.i(LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                        Log.i(LOG_TAG, "Version: " + cert.getVersion());
                        Log.i(LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                        Log.i(LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                        Log.i(LOG_TAG, "---------------------------");

                        // Make sure that it hasn't expired.
                        cert.checkValidity();

                        // Verify the certificate's public key chain.
                        cert.verify(rootca.getPublicKey());
                    }
                } catch (InvalidKeyException e) {
                    error = e;
                } catch (NoSuchAlgorithmException e) {
                    error = e;
                } catch (NoSuchProviderException e) {
                    error = e;
                } catch (SignatureException e) {
                    error = e;
                }
            }
            if (null != error) {
                Log.e(LOG_TAG, "Certificate error", error);
                throw new CertificateException(error);
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return acceptedIssuers;
        }
    } }, null);

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}

From source file:wptools.lib.Misc.java

/**
 * Bypass the normal SSL certificate authentication. If the passed
 * fingerprint is null, bypasses all authentication (dangerous).
 * Else trust anything whose chain contains a cert with the specified
 * fingerprint./*from www. java 2  s.  co m*/
 * @param fing      Fingerprint
 */
public static void bypassSslAuth(final byte[] fing) {
    // Determine fingerprint type from its length
    final String type;
    if (fing == null) {
        type = null;
    } else {
        switch (fing.length) {
        case MD5_LEN:
            type = "MD5";
            break;
        case SHA1_LEN:
            type = "SHA-1";
            break;
        case SHA256_LEN:
            type = "SHA-256";
            break;
        default:
            throw new IllegalArgumentException("Invalid hash.");
        }
    }

    // Create a trust manager
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
            matchFing(certs);
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
            matchFing(certs);
        }

        private void matchFing(X509Certificate[] certs) throws CertificateException {
            if (fing == null)
                return;
            MessageDigest md = null;
            try {
                md = MessageDigest.getInstance(type);
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException(e);
            }
            for (X509Certificate cert : certs) {
                md.reset();
                if (Arrays.equals(md.digest(cert.getEncoded()), fing))
                    return;
            }
            throw new CertificateException("No matching fingerprint found.");
        }
    } };

    // Install the trust manager
    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    // Create empty HostnameVerifier
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    };

    try {
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (KeyManagementException e) {
        throw new RuntimeException(e);
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:cn.geowind.takeout.verify.CcopHttpClient.java

/**
 * SSL/*w  w w  .  ja  v  a2  s .co  m*/
 * 
 * @param hostname
 *            ??IP??
 * @param protocol
 *            ????TLS-??
 * @param port
 *            ??
 * @param scheme
 *            ????
 * @return HttpClient
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public DefaultHttpClient registerSSL(String hostname, String protocol, int port, String scheme)
        throws NoSuchAlgorithmException, KeyManagementException {

    // HttpClient
    DefaultHttpClient httpclient = new DefaultHttpClient();
    // SSL
    SSLContext ctx = SSLContext.getInstance(protocol);
    // ???
    X509TrustManager tm = new X509TrustManager() {
        /**
         * CA??
         */
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        /**
         * ???
         * 
         * @param chain
         *            ?
         * @param authType
         *            ???authTypeRSA
         */
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            if (chain == null || chain.length == 0)
                throw new IllegalArgumentException("null or zero-length certificate chain");
            if (authType == null || authType.length() == 0)
                throw new IllegalArgumentException("null or zero-length authentication type");

            boolean br = false;
            Principal principal = null;
            for (X509Certificate x509Certificate : chain) {
                principal = x509Certificate.getSubjectX500Principal();
                if (principal != null) {
                    br = true;
                    return;
                }
            }
            if (!br) {
                throw new CertificateException("????");
            }
        }

        /**
         * ??
         */
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }
    };

    // ?SSL
    ctx.init(null, new TrustManager[] { tm }, new java.security.SecureRandom());
    // SSL
    SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme sch = new Scheme(scheme, port, socketFactory);
    // SSL
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);
    return httpclient;
}

From source file:com.tmount.business.cloopen.util.CcopHttpClient.java

/**
 * SSL//  ww w  . j ava2  s  .  c om
 * @param hostname ??IP??
 * @param protocol ????TLS-??
 * @param port ??
 * @param scheme ????
 * @return HttpClient
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public DefaultHttpClient registerSSL(String hostname, String protocol, int port, String scheme)
        throws NoSuchAlgorithmException, KeyManagementException {

    //HttpClient
    DefaultHttpClient httpclient = new DefaultHttpClient();
    //SSL
    SSLContext ctx = SSLContext.getInstance(protocol);
    //???
    X509TrustManager tm = new X509TrustManager() {

        /**
         * ??
         */
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
            //?   ?   
        }

        /**
         * ???
         * @param chain ?
         * @param authType ???authTypeRSA
         */
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
            if (chain == null || chain.length == 0)
                throw new IllegalArgumentException("null or zero-length certificate chain");
            if (authType == null || authType.length() == 0)
                throw new IllegalArgumentException("null or zero-length authentication type");

            boolean br = false;
            Principal principal = null;
            for (X509Certificate x509Certificate : chain) {
                principal = x509Certificate.getSubjectX500Principal();
                if (principal != null) {
                    br = true;
                    return;
                }
            }
            if (!br) {
                throw new CertificateException("????");
            }
        }

        /**
         * CA??
         */
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    };

    //?SSL
    ctx.init(null, new TrustManager[] { tm }, new java.security.SecureRandom());
    //SSL
    SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme sch = new Scheme(scheme, port, socketFactory);
    //SSL
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);
    return httpclient;
}

From source file:ee.ria.xroad.proxy.messagelog.TestUtil.java

static GlobalConfProvider getGlobalConf() {
    return new EmptyGlobalConf() {
        @Override/*from   w  w  w .  j  a  va2  s .co  m*/
        public List<X509Certificate> getTspCertificates() throws CertificateException {
            try {
                return Arrays.asList(CryptoUtils.readCertificate(TSP_CERT));
            } catch (IOException e) {
                throw new CertificateException(e);
            }
        }
    };
}

From source file:FileSystemDirectoryCertStore.java

/**
 * Creates a new instance over a directory using the specified extensions
 * @param dirPath the path for the base directory
 * @param certsFilesExts extensions for included certificate files
 * @param crlsFilesExts  extensions for included CRL files
 * @throws CertificateException if there's an error reading the certificates
 * @throws CRLException if there's an error reading the CRLs
 *///from  w  w  w .j a  va2 s.  c  om
public FileSystemDirectoryCertStore(String dirPath, final String[] certsFilesExts, final String[] crlsFilesExts)
        throws CertificateException, CRLException {
    File dir = new File(dirPath);
    if (!dir.exists() || !dir.isDirectory())
        throw new IllegalArgumentException("Specified path doesn't exist or doesn't refer a directory");

    Collection contentList = new ArrayList();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    transverseDirToFindContent(dir, contentList, certsFilesExts, crlsFilesExts, cf);

    try {
        this.content = CertStore.getInstance("Collection", new CollectionCertStoreParameters(contentList));
        return;
    } catch (InvalidAlgorithmParameterException ex) {
    } catch (NoSuchAlgorithmException ex) {
    }
    // ToDo: this is a bit ugly!
    throw new CertificateException("Error getting Collection CertStore");
}

From source file:at.gv.egiz.bku.spring.PKITrustManager.java

@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

    if (pkiProfile == null) {
        throw new CertificateException("No PKI profile set. Configuration error.");
    }//from  ww  w  .j ava  2  s. c  o m

    if (configurationFacade.disableAllSslChecks()) {
        log.warn("SSL certificate validation disabled. " + "Accepted certificate {}.", chain[0].getSubjectDN());
    } else {

        iaik.x509.X509Certificate[] certs = convertCerts(chain);

        TransactionId tid = new MDCTransactionId();
        try {
            PKIModule pkiModule = PKIFactory.getInstance().getPKIModule(pkiProfile);
            if (!pkiModule.validateCertificate(new Date(), certs[0], certs, null, tid).isCertificateValid()) {
                throw new CertificateException("Certificate not valid.");
            }
        } catch (PKIException e) {
            log.warn("Failed to validate certificate.", e);
            throw new CertificateException("Failed to validate certificate. " + e.getMessage());
        }

    }

}

From source file:be.fedict.eid.idp.sp.protocol.openid.OpenIDTrustManager.java

/**
 * {@inheritDoc}/*w w  w.j  a  va 2  s  .co  m*/
 */
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    LOG.debug("check server trusted");
    LOG.debug("auth type: " + authType);
    if (null == this.serverCertificate) {
        LOG.debug("trusting all server certificates");
        return;
    }
    if (!this.serverCertificate.equals(chain[0])) {
        throw new CertificateException("untrusted server certificate");
    }
}