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.hyperic.util.security.DatabaseSSLProviderImpl.java

private X509TrustManager getCustomTrustManager(final X509TrustManager defaultTrustManager,
        final KeystoreConfig keystoreConfig, final boolean acceptUnverifiedCertificates,
        final KeyStore trustStore) {
    return new X509TrustManager() {
        private final Log log = LogFactory.getLog(X509TrustManager.class);

        public X509Certificate[] getAcceptedIssuers() {
            return defaultTrustManager.getAcceptedIssuers();
        }/*from  w  ww  . j a  va 2s  .  c o m*/

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                defaultTrustManager.checkServerTrusted(chain, authType);
            } catch (CertificateException e) {
                CertificateExpiredException expiredCertException = getCertExpiredException(e);
                if (expiredCertException != null) {
                    log.error("Fail the connection because received certificate is expired. "
                            + "Please update the certificate.", expiredCertException);
                    throw new CertificateException(e);
                }
                if (acceptUnverifiedCertificates) {
                    log.info("Import the certification. (Received certificate is not trusted by keystore)");
                    importCertificate(chain);
                } else {
                    log.warn(
                            "Fail the connection because received certificate is not trusted by keystore: alias="
                                    + keystoreConfig.getAlias() + ", path=" + keystoreConfig.getFilePath());
                    log.debug(
                            "Fail the connection because received certificate is not trusted by keystore: alias="
                                    + keystoreConfig.getAlias() + ", path=" + keystoreConfig.getFilePath()
                                    + ", acceptUnverifiedCertificates=" + acceptUnverifiedCertificates,
                            e);
                    throw new CertificateException(e);
                }
            }
        }

        private CertificateExpiredException getCertExpiredException(Exception e) {
            while (e != null) {
                if (e instanceof CertificateExpiredException) {
                    return (CertificateExpiredException) e;
                }
                e = (Exception) e.getCause();
            }
            return null;
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            defaultTrustManager.checkClientTrusted(chain, authType);
        }

        private void importCertificate(X509Certificate[] chain) throws CertificateException {
            FileOutputStream keyStoreFileOutputStream = null;
            boolean hasLock = false;
            final boolean debug = log.isDebugEnabled();
            final StopWatch watch = new StopWatch();
            try {
                for (X509Certificate cert : chain) {
                    String[] cnValues = AbstractVerifier.getCNs(cert);
                    String alias;

                    if (cnValues != null && cnValues.length > 0) {
                        alias = cnValues[0];
                    } else {
                        alias = "UnknownCN";
                    }

                    alias += "-ts=" + System.currentTimeMillis();

                    trustStore.setCertificateEntry(alias, cert);
                }
                KEYSTORE_WRITER_LOCK.lockInterruptibly();
                hasLock = true;
                keyStoreFileOutputStream = new FileOutputStream(keystoreConfig.getFilePath());
                trustStore.store(keyStoreFileOutputStream, keystoreConfig.getFilePassword().toCharArray());
            } catch (FileNotFoundException e) {
                // Can't find the keystore in the path
                log.error("Can't find the keystore in " + keystoreConfig.getFilePath() + ". Error message:"
                        + e.getMessage(), e);
            } catch (NoSuchAlgorithmException e) {
                log.error("The algorithm is not supported. Error message:" + e.getMessage(), e);
            } catch (Exception e) {
                // expect KeyStoreException, IOException
                log.error("Exception when trying to import certificate: " + e.getMessage(), e);
            } finally {
                close(keyStoreFileOutputStream);
                keyStoreFileOutputStream = null;
                if (hasLock) {
                    KEYSTORE_WRITER_LOCK.unlock();
                }
                if (debug)
                    log.debug("importCert: " + watch);
            }
        }

        private void close(FileOutputStream keyStoreFileOutputStream) {
            if (keyStoreFileOutputStream != null) {
                try {
                    keyStoreFileOutputStream.close();
                } catch (IOException e) {
                    log.error(e, e);
                }
            }
        }
    };
}

From source file:be.fedict.eid.idp.sp.protocol.saml2.artifact.ArtifactServiceClient.java

/**
 * If set, unilateral TLS authentication will occur, verifying the server
 * {@link X509Certificate} specified against the {@link PublicKey}.
 * /*from w  ww.  ja va2 s  .c o  m*/
 * @param publicKey
 *            public key to validate server TLS certificate against.
 */
public void setServicePublicKey(final PublicKey publicKey) {

    // Create TrustManager
    TrustManager[] trustManager = { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {

            return null;
        }

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

            X509Certificate serverCertificate = chain[0];
            LOG.debug("server X509 subject: " + serverCertificate.getSubjectX500Principal().toString());
            LOG.debug("authentication type: " + authType);
            if (null == publicKey) {
                return;
            }

            try {
                serverCertificate.verify(publicKey);
                LOG.debug("valid server certificate");
            } catch (InvalidKeyException e) {
                throw new CertificateException("Invalid Key");
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException("No such algorithm");
            } catch (NoSuchProviderException e) {
                throw new CertificateException("No such provider");
            } catch (SignatureException e) {
                throw new CertificateException("Wrong signature");
            }
        }

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

            throw new CertificateException("this trust manager cannot be used as server-side trust manager");
        }
    } };

    // Create SSL Context
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        SecureRandom secureRandom = new SecureRandom();
        sslContext.init(null, trustManager, secureRandom);
        LOG.debug("SSL context provider: " + sslContext.getProvider().getName());

        // Setup TrustManager for validation
        Map<String, Object> requestContext = ((BindingProvider) this.port).getRequestContext();
        requestContext.put(JAXWSProperties.SSL_SOCKET_FACTORY, sslContext.getSocketFactory());

    } catch (KeyManagementException e) {
        String msg = "key management error: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    } catch (NoSuchAlgorithmException e) {
        String msg = "TLS algo not present: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    }
}

From source file:controller.CCInstance.java

public final ArrayList<CCAlias> loadKeyStoreAndAliases()
        throws LibraryNotLoadedException, KeyStoreNotLoadedException, CertificateException, KeyStoreException,
        LibraryNotFoundException, AliasException {
    String pkcs11config = "name = SmartCard\n library = ";
    String path = null;//w  w  w  . j  av  a  2 s.  co  m
    if (SystemUtils.IS_OS_WINDOWS) {
        path = System.getenv("HOMEDRIVE") + "\\windows\\system32\\pteidpkcs11.dll";
    } else if (SystemUtils.IS_OS_LINUX) {
        path = "/usr/local/lib/libpteidpkcs11.so";
    } else if (SystemUtils.IS_OS_MAC_OSX) {
        path = "/usr/local/lib/pteidpkcs11.bundle";
    }

    if (null == path) {
        throw new LibraryNotLoadedException(Bundle.getBundle().getString("unknownOS"));
    } else if (new File(path).exists()) {
        pkcs11config += path;
    } else {
        String res = userLoadLibraryPKCS11();
        if (null != res) {
            pkcs11config += res;
        }
        throw new LibraryNotFoundException(Bundle.getBundle().getString("libraryNotFound"));
    }
    final byte[] pkcs11configBytes;
    try {
        pkcs11configBytes = pkcs11config.getBytes();
    } catch (Exception eiie) {
        Logger.getLogger().addEntry(eiie);
        throw new LibraryNotFoundException(Bundle.getBundle().getString("libraryDoesNotExist"));
    }
    final ByteArrayInputStream configStream = new ByteArrayInputStream(pkcs11configBytes);
    try {
        pkcs11Provider = new sun.security.pkcs11.SunPKCS11(configStream);
        pkcs11Provider.setCallbackHandler(new CallbackHandler() {

            @Override
            public void handle(javax.security.auth.callback.Callback[] callbacks)
                    throws IOException, UnsupportedCallbackException {
                for (javax.security.auth.callback.Callback c : callbacks) {
                    if (c instanceof PasswordCallback) {
                        ((PasswordCallback) c).setPassword(null);
                    }
                }
            }
        });
    } catch (Exception eiie) {
        Logger.getLogger().addEntry(eiie);
        throw new LibraryNotLoadedException(Bundle.getBundle().getString("libraryNotLoaded"));
    }

    Security.addProvider(pkcs11Provider);

    try {
        pkcs11ks = KeyStore.getInstance("PKCS11");
        pkcs11ks.load(null, null);
    } catch (Exception e) {
        Logger.getLogger().addEntry(e);
        throw new KeyStoreNotLoadedException(Bundle.getBundle().getString("keystoreNotLoaded"));
    }

    final Enumeration aliasesEnum = pkcs11ks.aliases();
    aliasList.clear();

    while (aliasesEnum.hasMoreElements()) {
        final String alias = (String) aliasesEnum.nextElement();
        if (null != alias) {
            if (alias.isEmpty()) {
                throw new AliasException(Bundle.getBundle().getString("blankAlias"));
            } else {
                final Certificate[] certChain = pkcs11ks.getCertificateChain(alias);
                if (null != certChain) {
                    if (CCAlias.ASSINATURA.equals(alias)) {
                        if (0 == certChain.length) {
                            throw new CertificateException(Bundle.getBundle().getString("chainInvalidFormat"));
                        } else {
                            final Certificate cert = certChain[0];
                            try {
                                ((X509Certificate) cert).checkValidity();
                                if (1 <= certChain.length) {
                                    final CCAlias ccAliasTemp = new CCAlias(alias, certChain);
                                    aliasList.add(ccAliasTemp);
                                }
                            } catch (CertificateExpiredException cee) {
                                Logger.getLogger().addEntry(cee);
                                throw new CertificateException(Bundle.getBundle().getString("aliasCertificate")
                                        + " " + alias + " " + Bundle.getBundle().getString("expired") + "!");
                            } catch (CertificateNotYetValidException cee) {
                                Logger.getLogger().addEntry(cee);
                                throw new CertificateException(
                                        Bundle.getBundle().getString("aliasCertificate") + " " + alias + " "
                                                + Bundle.getBundle().getString("notYetValid") + "!");
                            }
                        }
                    }
                }
            }
        }
    }
    return aliasList;
}

From source file:org.seedstack.seed.crypto.internal.EncryptionServiceFactoryTest.java

/**
 * Test method for/*w  w w. j av a  2s  . com*/
 * {@link org.seedstack.seed.crypto.internal.EncryptionServiceFactory#createEncryptionService(org.seedstack.seed.crypto.internal.KeyStoreDefinition, org.seedstack.seed.crypto.internal.CertificateDefinition)}
 * . Test a {@link CertificateException} if keystore can not be loaded.
 *
 * @throws Exception if an error occurred
 */
@Test(expected = RuntimeException.class)
public void testCreateEncryptionServiceWithKeystoreCertificateException(
        @Mocked final KeyStoreDefinition keyStoreDefinition,
        @Mocked final CertificateDefinition certificateDefinition, @Mocked final KeyStore keyStore,
        @Mocked final FileInputStream file,
        @SuppressWarnings("unused") @Mocked final EncryptionServiceImpl asymetricCrypting) throws Exception {
    new Expectations() {
        final String pathToKeystore = "pathToKeystore";
        final String password = "password";

        {
            keyStoreDefinition.getPath();
            returns(pathToKeystore);

            KeyStore.getInstance(KeyStore.getDefaultType());
            returns(keyStore);

            new FileInputStream(pathToKeystore);
            result = file;

            keyStoreDefinition.getPassword();
            returns(password);

            keyStore.load(file, password.toCharArray());
            result = new CertificateException("dummy exception");
        }
    };

    EncryptionServiceFactory factory = new EncryptionServiceFactory();
    factory.createEncryptionService(keyStoreDefinition, certificateDefinition);

}

From source file:org.globus.security.stores.PEMKeyStore.java

/**
 * Load the keystore from the supplied input stream. Unlike many other
 * implementations of keystore (most notably the default JKS
 * implementation), the input stream does not hold the keystore objects.
 * Instead, it must be a properties file defining the locations of the
 * keystore objects. The password is not used.
 * /*from   w  ww . j a v  a2s.  com*/
 * @param inputStream
 *            An input stream to the properties file.
 * @param chars
 *            The password is not used.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
@Override
public void engineLoad(InputStream inputStream, char[] chars)
        throws IOException, NoSuchAlgorithmException, CertificateException {
    try {
        Properties properties = new Properties();
        properties.load(inputStream);
        if (properties.size() == 0) {
            throw new CertificateException("Properties file for configuration was null");
        }
        String defaultDirectoryString = properties.getProperty(DEFAULT_DIRECTORY_KEY);
        String directoryListString = properties.getProperty(DIRECTORY_LIST_KEY);
        String proxyFilename = properties.getProperty(PROXY_FILENAME);
        String certFilename = properties.getProperty(CERTIFICATE_FILENAME);
        String keyFilename = properties.getProperty(KEY_FILENAME);
        initialize(defaultDirectoryString, directoryListString, proxyFilename, certFilename, keyFilename);
    } finally {
        try {
            inputStream.close();
        } catch (IOException e) {
            logger.log(Level.INFO, "Error closing inputStream", e);
        }
    }
}

From source file:org.globus.gsi.stores.PEMKeyStore.java

/**
 * Load the keystore from the supplied input stream. Unlike many other
 * implementations of keystore (most notably the default JKS
 * implementation), the input stream does not hold the keystore objects.
 * Instead, it must be a properties file defining the locations of the
 * keystore objects. The password is not used.
 *
 * @param inputStream// ww w  .j a  va  2 s  . c om
 *            An input stream to the properties file.
 * @param chars
 *            The password is not used.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
@Override
public void engineLoad(InputStream inputStream, char[] chars)
        throws IOException, NoSuchAlgorithmException, CertificateException {
    try {
        Properties properties = new Properties();
        if (inputStream != null) {
            properties.load(inputStream);
            if (properties.size() == 0) {
                throw new CertificateException("Properties file for configuration was empty?");
            }
        } else {
            if (chars == null) {
                // keyStore.load(null,null) -> in memory only keystore
                inMemoryOnly = true;
            }
        }
        String defaultDirectoryString = properties.getProperty(DEFAULT_DIRECTORY_KEY);
        String directoryListString = properties.getProperty(DIRECTORY_LIST_KEY);
        String proxyFilename = properties.getProperty(PROXY_FILENAME);
        String certFilename = properties.getProperty(CERTIFICATE_FILENAME);
        String keyFilename = properties.getProperty(KEY_FILENAME);
        initialize(defaultDirectoryString, directoryListString, proxyFilename, certFilename, keyFilename);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                logger.info("Error closing inputStream", e);
            }
        }
    }
}

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

/**
 * Returns the DN extracted from the client certificate.
 *
 * If the client auth setting is WANT or NONE and a certificate is not present (and {@code respectClientAuth} is {@code true}), this method will return {@code null}.
 * If the client auth is NEED, it will throw a {@link CertificateException}.
 *
 * @param sslSocket the SSL Socket//from ww w.j  av  a 2s .c o m
 * @return the extracted DN
 * @throws CertificateException if there is a problem parsing the certificate
 */
private static String extractPeerDNFromClientSSLSocket(SSLSocket sslSocket) throws CertificateException {
    String dn = null;

    /** The clientAuth value can be "need", "want", or "none"
     * A client must send client certificates for need, should for want, and will not for none.
     * This method should throw an exception if none are provided for need, return null if none are provided for want, and return null (without checking) for none.
     */

    ClientAuth clientAuth = getClientAuthStatus(sslSocket);
    logger.debug("SSL Socket client auth status: {}", clientAuth);

    if (clientAuth != ClientAuth.NONE) {
        try {
            final Certificate[] certChains = sslSocket.getSession().getPeerCertificates();
            if (certChains != null && certChains.length > 0) {
                X509Certificate x509Certificate = convertAbstractX509Certificate(certChains[0]);
                dn = x509Certificate.getSubjectDN().getName().trim();
                logger.debug("Extracted DN={} from client certificate", dn);
            }
        } catch (SSLPeerUnverifiedException e) {
            if (e.getMessage().equals(PEER_NOT_AUTHENTICATED_MSG)) {
                logger.error("The incoming request did not contain client certificates and thus the DN cannot"
                        + " be extracted. Check that the other endpoint is providing a complete client certificate chain");
            }
            if (clientAuth == ClientAuth.WANT) {
                logger.warn(
                        "Suppressing missing client certificate exception because client auth is set to 'want'");
                return dn;
            }
            throw new CertificateException(e);
        }
    }
    return dn;
}

From source file:org.globus.gsi.util.CertificateUtil.java

private static GSIConstants.CertificateType processCN(X509Extensions extensions,
        GSIConstants.CertificateType type, ASN1Sequence ava) throws CertificateException {
    X509Extension ext;/*from  w  w w. j  a v  a  2  s  .c  o  m*/
    String value = ((ASN1String) ava.getObjectAt(1)).getString();
    GSIConstants.CertificateType certType = type;
    if (value.equalsIgnoreCase("proxy")) {
        certType = GSIConstants.CertificateType.GSI_2_PROXY;
    } else if (value.equalsIgnoreCase("limited proxy")) {
        certType = GSIConstants.CertificateType.GSI_2_LIMITED_PROXY;
    } else if (extensions != null) {
        boolean gsi4 = true;
        // GSI_4
        ext = extensions.getExtension(ProxyCertInfo.OID);
        if (ext == null) {
            // GSI_3
            ext = extensions.getExtension(ProxyCertInfo.OLD_OID);
            gsi4 = false;
        }
        if (ext != null) {
            if (ext.isCritical()) {
                certType = processCriticalExtension(ext, gsi4);
            } else {
                String err = "proxyCertCritical";
                throw new CertificateException(err);
            }
        }
    }

    return certType;
}

From source file:com.aivarsda.certpinninglib.HttpsPinner.java

/**
 * Will match the _trustedPins against the certificate chain, to validate
 * the specific certificate by checking if it has one of the trusted pins.
 * /*from  w  w w  .j a  v  a 2s  .c  o  m*/
 * @param certificate Certificate to validate with the pin.
 * @return True - certificate has one of the trusted pins. False - otherwise.
 * @throws CertificateException
 */
private boolean hasTrustedPin(X509Certificate certificate) throws CertificateException {
    try {
        boolean hasTrustedPin = false;
        final MessageDigest digest = MessageDigest.getInstance("SHA1");
        final byte[] encodedPublicKey = certificate.getPublicKey().getEncoded();
        final byte[] pin = digest.digest(encodedPublicKey);
        String strPin = Hex.bytesToHexString(pin);

        for (byte[] validPin : this._trustedPins) {
            if (Arrays.equals(validPin, pin)) {
                hasTrustedPin = true;
                break;
            }
        }

        // Remove logging if not needed
        Logger.logCertificate(certificate, true, strPin, hasTrustedPin);

        return hasTrustedPin;
    } catch (NoSuchAlgorithmException nsae) {
        throw new CertificateException(nsae);
    }
}

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

/**
 * Returns the DN extracted from the server certificate.
 *
 * @param socket the SSL Socket/*from   ww  w .j  av a  2  s .  c o m*/
 * @return the extracted DN
 * @throws CertificateException if there is a problem parsing the certificate
 */
private static String extractPeerDNFromServerSSLSocket(Socket socket) throws CertificateException {
    String dn = null;
    if (socket instanceof SSLSocket) {
        final SSLSocket sslSocket = (SSLSocket) socket;
        try {
            final Certificate[] certChains = sslSocket.getSession().getPeerCertificates();
            if (certChains != null && certChains.length > 0) {
                X509Certificate x509Certificate = convertAbstractX509Certificate(certChains[0]);
                dn = x509Certificate.getSubjectDN().getName().trim();
                logger.debug("Extracted DN={} from server certificate", dn);
            }
        } catch (SSLPeerUnverifiedException e) {
            if (e.getMessage().equals(PEER_NOT_AUTHENTICATED_MSG)) {
                logger.error("The server did not present a certificate and thus the DN cannot"
                        + " be extracted. Check that the other endpoint is providing a complete certificate chain");
            }
            throw new CertificateException(e);
        }
    }
    return dn;
}