Example usage for java.security.cert CertificateException getMessage

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

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.openanzo.client.AnzoTrustManager.java

private void handleCertificateException(CertificateException ce, X509Certificate[] chain)
        throws CertificateException {
    if (trustAll) {
        return;// ww  w .  jav  a2 s . c om
    }

    System.err.println(ce.getMessage());
    System.err.println("Certificate Information: \n");
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(chain[0].getNotBefore().getTime());
    System.err.println("Creation Date: " + MONTHS[cal.get(Calendar.MONTH)] + " "
            + cal.get(Calendar.DAY_OF_MONTH) + ", " + cal.get(Calendar.YEAR));
    //System.err.println("Entry type: " + chain[0].getType());
    System.err.println("Certificate chain length: " + chain.length);

    // print some information about the certificate(s) that failed
    int i = 1;
    for (X509Certificate cert : chain) {
        System.err.println("Certificate[" + i++ + "]:");
        System.err.println("Owner: " + cert.getSubjectX500Principal().toString());
        System.err.println("Issuer: " + cert.getIssuerX500Principal().toString());

        String serialNum = new String(Hex.encodeHex(cert.getSerialNumber().toByteArray()));
        System.err.println("Serial Number: " + serialNum);
        System.err.println(
                "Valid from: " + cert.getNotBefore().toString() + " until: " + cert.getNotAfter().toString());
        System.err.println("Certificate fingerprints: ");
        try {
            byte[] sig = cert.getEncoded();
            System.err.println("\tMD5: " + getHash(sig, "MD5"));
            System.err.println("\tSHA1: " + getHash(sig, "SHA1"));
        } catch (NoSuchAlgorithmException e) {
        }
        System.err.println("\tSignature Algorithm Name: " + cert.getSigAlgName());
        System.err.println("\tVersion: " + cert.getVersion());
        System.err.println("-----------------------------------------------------");
    }
    System.err.println("Would you like to accept this certificate? (o)nce, (a)lways, (n)o");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line = "";
    try {
        line = in.readLine();
    } catch (IOException e) {
        CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
        System.exit(1);
    }
    if (Character.toLowerCase(line.charAt(0)) == 'o') {
        return;
    } else if (Character.toLowerCase(line.charAt(0)) == 'a') {
        try {
            String truststoreType = System.getProperty("javax.net.ssl.trustStoreType", "JCEKS");
            String truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_PWORD);

            String truststorePath = System.getProperty("javax.net.ssl.trustStore");
            if (truststorePath == null) { // there is no trust store location in the user's settings.trig file
                String userHome = System.getProperty("user.home");
                if (userHome == null)
                    throw new AnzoException(ExceptionConstants.CLIENT.FAILED_INITIALIZE_TRUST_MANAGER,
                            "User's home directory is not specified");
                File truststoreFile = new File(new File(userHome, ANZO_DIR), DEFAULT_CLIENT_TRUST);
                truststorePath = truststoreFile.getCanonicalPath();
                if (!truststoreFile.exists())
                    openTruststore(truststoreType, truststorePath, truststorePassword);
            } else {
                truststorePath = CommandContext.preprocessString(truststorePath);
                File truststoreFile = new File(truststorePath);

                if (!truststoreFile.exists()) {
                    System.err.println("Could not find the specified trust store file at:");
                    System.err.println(truststoreFile.getCanonicalPath());
                    System.err.println(
                            "The trust store file is used for permanently trusting server certificates that");
                    System.err.println("are not trusted by default.");
                    System.err.println(
                            "Would you like to create a new trust store file at the specified location?");
                    System.err.println("(y)es, (n)o");
                    try {
                        line = in.readLine();
                    } catch (IOException e) {
                        CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
                        System.exit(1);
                    }
                    if (Character.toLowerCase(line.charAt(0)) == 'y')
                        openTruststore(truststoreType, truststorePath, truststorePassword);
                    else
                        System.exit(1);
                }
            }

            KeystoreUtils.addTrustedCert(truststorePath, truststoreType, truststorePassword,
                    "imported_" + System.currentTimeMillis(), chain[0]);
        } catch (AnzoException ae) {
            System.err.println("Error importing certificate into truststore: ");
            CommandLineInterface.DEFAULT_CONSOLE.printException(ae, showTrace);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error importing certificate into truststore: ");
            CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
            System.exit(1);
        }
    } else {
        System.exit(1); // if the user does not want to trust the certificate then exit
    }
}

From source file:be.fedict.eid.idp.admin.webapp.bean.ConfigBean.java

@Override
@End//w  ww. j a  v a  2 s.  c o  m
public String saveApplet() {
    this.log.debug("save applet config");

    // Applet config
    if (null != this.certificateBytes) {
        try {
            this.appletConfig.setServerCertificate(getCertificate(this.certificateBytes));
        } catch (CertificateException e) {
            this.log.error("Certificate exception: " + e.getMessage(), e);
            this.facesMessages.addToControl("upload", "Invalid certificate");
            return null;
        }
        this.configuration.setAppletConfig(this.appletConfig);
    }

    this.configuration.setValue(ConfigProperty.REMOVE_CARD, this.removeCard);
    this.configuration.setValue(ConfigProperty.TRANSACTION_MESSAGE_SIGNING, this.transactionMessageSigning);
    this.configuration.setValue(ConfigProperty.OMIT_SECURE_CHANNEL_BINDING, this.omitSecureChannelBinding);

    this.selectedTab = ConfigurationTab.tab_applet.name();
    return "success";
}

From source file:mobac.mapsources.loader.MapPackManager.java

/**
 * Performs on map sources online update
 * //from  w  ww.j a  va  2s  .  c om
 * @return <ul>
 *         <li>0: no change in online md5 sum file (based on ETag)</li>
 *         <li>-1: Online md5 file is empty indicationg that this MOBAc versiosn is no longer supported</li>
 *         <li>x>0: Number of updated map packs</li>
 *         </ul>
 * @throws IOException
 */
public int updateMapPacks() throws UpdateFailedException, UnrecoverableDownloadException, IOException {
    String updateBaseUrl = System.getProperty("mobac.updatebaseurl");
    if (updateBaseUrl == null)
        throw new RuntimeException("Update base url not present");

    cleanMapPackDir();
    String md5sumList = downloadMD5SumList();
    if (md5sumList == null)
        return 0; // no new md5 file available
    if (md5sumList.length() == 0)
        return -1; // empty file means - outdated version
    int updateCount = 0;
    String[] outdatedMapPacks = searchForOutdatedMapPacks(md5sumList);
    for (String mapPack : outdatedMapPacks) {
        log.debug("Updaing map pack: " + mapPack);
        try {
            File newMapPackFile = downloadMapPack(updateBaseUrl, mapPack);
            try {
                testMapPack(newMapPackFile);
            } catch (CertificateException e) {
                // Certificate validation failed
                log.error(e.getMessage(), e);
                Utilities.deleteFile(newMapPackFile);
                continue;
            }
            log.debug("Verification of map pack \"" + mapPack + "\" passed successfully");

            // Check if the downloaded version is newer
            int newRev = getMapPackRevision(newMapPackFile);
            File oldMapPack = new File(mapPackDir, mapPack);
            int oldRev = -1;
            if (oldMapPack.isFile())
                oldRev = getMapPackRevision(oldMapPack);
            if (newRev < oldRev) {
                log.warn("Downloaded map pack was older than existing map pack - ignoring update");
                Utilities.deleteFile(newMapPackFile);
            } else {
                String name = newMapPackFile.getName();
                name = name.replace(".unverified", ".new");
                File f = new File(newMapPackFile.getParentFile(), name);
                // Change file extension
                Utilities.renameFile(newMapPackFile, f);
                updateCount++;
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
    return updateCount;
}

From source file:osmcd.mapsources.loader.MapPackManager.java

/**
 * Performs on map sources online update
 * // w  w  w.  j a v  a 2  s  . c o m
 * @return <ul>
 *         <li>0: no change in online md5 sum file (based on ETag)</li>
 *         <li>-1: Online md5 file is empty indicationg that this OSMCB version is no longer supported</li>
 *         <li>x>0: Number of updated map packs</li>
 *         </ul>
 * @throws IOException
 */
public int updateMapPacks() throws UpdateFailedException, UnrecoverableDownloadException, IOException {
    String updateBaseUrl = System.getProperty("osmcd.updatebaseurl");
    if (updateBaseUrl == null)
        throw new RuntimeException("Update base url not present");

    cleanMapPackDir();
    String md5sumList = downloadMD5SumList();
    if (md5sumList == null)
        return 0; // no new md5 file available
    if (md5sumList.length() == 0)
        return -1; // empty file means - outdated version
    int updateCount = 0;
    String[] outdatedMapPacks = searchForOutdatedMapPacks(md5sumList);
    for (String mapPack : outdatedMapPacks) {
        log.debug("Updaing map pack: " + mapPack);
        try {
            File newMapPackFile = downloadMapPack(updateBaseUrl, mapPack);
            try {
                testMapPack(newMapPackFile);
            } catch (CertificateException e) {
                // Certificate validation failed
                log.error(e.getMessage(), e);
                Utilities.deleteFile(newMapPackFile);
                continue;
            }
            log.debug("Verification of map pack \"" + mapPack + "\" passed successfully");

            // Check if the downloaded version is newer
            int newRev = getMapPackRevision(newMapPackFile);
            File oldMapPack = new File(mapPackDir, mapPack);
            int oldRev = -1;
            if (oldMapPack.isFile())
                oldRev = getMapPackRevision(oldMapPack);
            if (newRev < oldRev) {
                log.warn("Downloaded map pack was older than existing map pack - ignoring update");
                Utilities.deleteFile(newMapPackFile);
            } else {
                String name = newMapPackFile.getName();
                name = name.replace(".unverified", ".new");
                File f = new File(newMapPackFile.getParentFile(), name);
                // Change file extension
                Utilities.renameFile(newMapPackFile, f);
                updateCount++;
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
    return updateCount;
}

From source file:org.commonjava.maven.galley.transport.htcli.internal.LocationSSLSocketFactory.java

private synchronized SSLSocketFactory getSSLFactory(final HttpLocation loc) throws IOException {
    //        logger.info( "Finding SSLSocketFactory for repo: {}", repo.getKey() );

    SSLSocketFactory factory = null; // repoFactories.get( repo );
    if (factory == null) {
        KeyStore ks = null;//from w ww.j  av a  2s  . c  o  m
        KeyStore ts = null;

        final String kcPem = loc.getKeyCertPem();
        final String kcPass = passwordManager.getPassword(new PasswordEntry(loc, PasswordEntry.KEY_PASSWORD));
        if (kcPem != null) {
            if (kcPass == null || kcPass.length() < 1) {
                logger.error("Invalid configuration. Location: {} cannot have an empty key password!",
                        loc.getUri());
                throw new IOException("Location: " + loc.getUri() + " is misconfigured!");
            }

            try {
                ks = SSLUtils.readKeyAndCert(kcPem, kcPass);

                //                    final StringBuilder sb = new StringBuilder();
                //                    sb.append( "Keystore contains the following certificates:" );
                //
                //                    for ( final Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements(); )
                //                    {
                //                        final String alias = aliases.nextElement();
                //                        final X509Certificate cert = (X509Certificate) ks.getCertificate( alias );
                //
                //                        if ( cert != null )
                //                        {
                //                            sb.append( "\n" )
                //                              .append( cert.getSubjectDN() );
                //                        }
                //                    }
                //                    sb.append( "\n" );
                //                    logger.info( sb.toString() );
            } catch (final CertificateException e) {
                logger.error(String.format(
                        "Invalid configuration. Location: %s has an invalid client certificate! Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final KeyStoreException e) {
                logger.error(String.format(
                        "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final NoSuchAlgorithmException e) {
                logger.error(String.format(
                        "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final InvalidKeySpecException e) {
                logger.error(
                        String.format("Invalid configuration. Invalid client key for repository: %s. Error: %s",
                                loc.getUri(), e.getMessage()),
                        e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            }
        }

        final String sPem = loc.getServerCertPem();
        //            logger.info( "Server certificate PEM:\n{}", sPem );
        if (sPem != null) {
            try {
                ts = SSLUtils.readCerts(sPem, loc.getHost());

                //                    final StringBuilder sb = new StringBuilder();
                //                    sb.append( "Trust store contains the following certificates:" );
                //
                //                    for ( final Enumeration<String> aliases = ts.aliases(); aliases.hasMoreElements(); )
                //                    {
                //                        final String alias = aliases.nextElement();
                //                        final X509Certificate cert = (X509Certificate) ts.getCertificate( alias );
                //                        if ( cert != null )
                //                        {
                //                            sb.append( "\n" )
                //                              .append( cert.getSubjectDN() );
                //                        }
                //                    }
                //                    sb.append( "\n" );
                //                    logger.info( sb.toString() );
            } catch (final CertificateException e) {
                logger.error(String.format(
                        "Invalid configuration. Location: %s has an invalid server certificate! Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final KeyStoreException e) {
                logger.error(String.format(
                        "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final NoSuchAlgorithmException e) {
                logger.error(String.format(
                        "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            }
        }

        if (ks != null || ts != null) {
            try {
                factory = new SSLSocketFactory(SSLSocketFactory.TLS, ks, kcPass, ts, null, null,
                        SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

                // repoFactories.put( repo, factory );
            } catch (final KeyManagementException e) {
                logger.error(
                        "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                        e, loc.getUri(), e.getMessage());
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final UnrecoverableKeyException e) {
                logger.error(
                        "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                        e, loc.getUri(), e.getMessage());
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final NoSuchAlgorithmException e) {
                logger.error(
                        "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                        e, loc.getUri(), e.getMessage());
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final KeyStoreException e) {
                logger.error(
                        "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                        e, loc.getUri(), e.getMessage());
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            }
        }
    }

    return factory;
}

From source file:eu.eidas.auth.engine.core.impl.SignSW.java

/**
 *
 * @param tokenSaml the object whose signature has to be checked
 * @param keyInfo the keyinfo retrieved from saml metadata
 * @throws SAMLEngineException//from   w  ww .j av a  2  s  .c  o m
 */
private void checkMetadataTrust(final SignableSAMLObject tokenSaml, KeyInfo keyInfo)
        throws SAMLEngineException {
    try {
        final List<Credential> metadataCred = new ArrayList<Credential>();

        metadataCred.add(getKeyInfoCredential(keyInfo));
        final X509Certificate currentSignatureCert = getSignatureCertificate(tokenSaml.getSignature());
        final BasicX509Credential currentSignatureX509Cred = new BasicX509Credential();
        currentSignatureX509Cred.setEntityCertificate(currentSignatureCert);

        checkTrust(currentSignatureX509Cred, metadataCred);
        checkSignatureCertificate(tokenSaml.getSignature(), metadataCred, true);
    } catch (CertificateException ce) {
        LOG.warn("ERROR : error creating certificate instance", ce.getMessage());
        LOG.debug("ERROR : error creating certificate instance", ce);
        throw new SAMLEngineException(ce);
    }

}

From source file:org.commonjava.util.jhttpc.HttpFactory.java

private SSLConnectionSocketFactory createSSLSocketFactory(final SiteConfig location) throws JHttpCException {
    SSLConnectionSocketFactory fac = (SSLConnectionSocketFactory) location.getAttribute(SSL_FACTORY_ATTRIB);
    if (fac != null) {
        return fac;
    }// w  w w.ja v a2  s  .  c  o  m

    KeyStore ks = null;
    KeyStore ts = null;

    final String kcPem = location.getKeyCertPem();

    final String kcPass = passwords.lookup(new PasswordKey(location, PasswordType.KEY));
    if (kcPem != null) {
        logger.debug("Adding client key/certificate from: {}", location);
        if (kcPass == null || kcPass.length() < 1) {
            logger.error("Invalid configuration. Location: {} cannot have an empty key password!",
                    location.getUri());
            throw new JHttpCException(
                    "Location: " + location.getUri() + " is misconfigured! Key password cannot be empty.");
        }

        try {
            logger.trace("Reading Client SSL key from:\n\n{}\n\n", kcPem);
            ks = SSLUtils.readKeyAndCert(kcPem, kcPass);

            logger.trace("Keystore contains the following certificates: {}", new CertEnumerator(ks, kcPass));
        } catch (final CertificateException e) {
            logger.error(String.format(
                    "Invalid configuration. Location: %s has an invalid client certificate! Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final KeyStoreException e) {
            logger.error(String.format(
                    "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final NoSuchAlgorithmException e) {
            logger.error(String.format(
                    "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final InvalidKeySpecException e) {
            logger.error(
                    String.format("Invalid configuration. Invalid client key for repository: %s. Error: %s",
                            location.getUri(), e.getMessage()),
                    e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (IOException e) {
            throw new JHttpCException("Failed to read client SSL key/certificate from: %s. Reason: %s", e,
                    location, e.getMessage());
        } catch (JHttpCException e) {
            throw new JHttpCException("Failed to read client SSL key/certificate from: %s. Reason: %s", e,
                    location, e.getMessage());
        }
    } else {
        logger.debug("No client key/certificate found");
    }

    final String sPem = location.getServerCertPem();

    //        logger.debug( "Server certificate PEM:\n{}", sPem );
    if (sPem != null) {
        logger.debug("Loading TrustStore (server SSL) information from: {}", location);
        try {
            logger.trace("Reading Server SSL cert from:\n\n{}\n\n", sPem);
            ts = SSLUtils.decodePEMTrustStore(sPem, location.getHost());

            logger.trace("Trust store contains the following certificates:\n{}", new CertEnumerator(ts, null));
        } catch (final CertificateException e) {
            logger.error(String.format(
                    "Invalid configuration. Location: %s has an invalid server certificate! Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final KeyStoreException e) {
            logger.error(String.format(
                    "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final NoSuchAlgorithmException e) {
            logger.error(String.format(
                    "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (IOException e) {
            throw new JHttpCException(
                    "Failed to read server SSL certificate(s) (or couldn't parse server hostname) from: %s. Reason: %s",
                    e, location, e.getMessage());
        }
    } else {
        logger.debug("No server certificates found");
    }

    if (ks != null || ts != null) {
        logger.debug("Setting up SSL context.");
        try {
            SSLContextBuilder sslBuilder = SSLContexts.custom().useProtocol(SSLConnectionSocketFactory.TLS);
            if (ks != null) {
                logger.trace("Loading key material for SSL context...");
                PrivateKeyStrategy pkStrategy = new MonolithicKeyStrategy();
                sslBuilder.loadKeyMaterial(ks, kcPass.toCharArray(), pkStrategy);
            }

            if (ts != null) {
                logger.trace("Loading trust material for SSL context...");

                SiteTrustType trustType = location.getTrustType();
                if (trustType == null) {
                    trustType = SiteTrustType.DEFAULT;
                }

                sslBuilder.loadTrustMaterial(ts, trustType.getTrustStrategy());
            }

            SSLContext ctx = sslBuilder.build();

            fac = new SSLConnectionSocketFactory(ctx, new DefaultHostnameVerifier());
            location.setAttribute(SSL_FACTORY_ATTRIB, fac);
            return fac;
        } catch (final KeyManagementException e) {
            logger.error(
                    "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                    e, location.getUri(), e.getMessage());
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final UnrecoverableKeyException e) {
            logger.error(
                    "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                    e, location.getUri(), e.getMessage());
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final NoSuchAlgorithmException e) {
            logger.error(
                    "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                    e, location.getUri(), e.getMessage());
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final KeyStoreException e) {
            logger.error(
                    "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                    e, location.getUri(), e.getMessage());
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        }
    } else {
        logger.debug("No SSL configuration present; no SSL context created.");
    }

    return null;
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#applyCertificateRequest(String, File, File, String)
 *///  w w w. j a  va 2s  . c o m
public synchronized boolean applyCertificateRequest(final String commonName, final File certificateFile,
        final File keystoreFile, final String storePassword) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#applyCertificateRequest(final String commonName, final File certificateFile, final File keystoreFile, final String storePassword) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", commonName);
        DEBUGGER.debug("Value: {}", certificateFile);
        DEBUGGER.debug("Value: {}", keystoreFile);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final File certificateDirectory = FileUtils
            .getFile(certConfig.getCertificateDirectory() + "/" + commonName);
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + commonName);

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("certificateDirectory: {}", certificateDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("certificateFile: {}", certificateFile);
        DEBUGGER.debug("keystoreFile: {}", keystoreFile);
    }

    boolean isComplete = false;
    FileInputStream certStream = null;
    FileOutputStream storeStream = null;
    FileInputStream keystoreInput = null;
    FileInputStream rootCertStream = null;
    FileInputStream intermediateCertStream = null;

    try {
        if (!(rootDirectory.exists())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(rootDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(certConfig.getRootCertificateFile().exists())) {
            throw new CertificateManagementException("Root certificate file does not exist. Cannot continue.");
        }

        if (!(certConfig.getIntermediateCertificateFile().exists())) {
            throw new CertificateManagementException(
                    "Intermediate certificate file does not exist. Cannot continue.");
        }

        if (!(storeDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Keystore directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(keystoreFile.canWrite())) {
            throw new CertificateManagementException(
                    "Unable to write to applicable keystore. Cannot continue.");
        }

        keystoreInput = FileUtils.openInputStream(keystoreFile);
        certStream = FileUtils.openInputStream(certificateFile);

        if (DEBUG) {
            DEBUGGER.debug("keystoreInput: {}", keystoreInput);
            DEBUGGER.debug("certStream: {}", certStream);
        }

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(keystoreInput, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        Key privateKey = keyStore.getKey(commonName, storePassword.toCharArray());
        CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

        if (DEBUG) {
            DEBUGGER.debug("CertificateFactory: {}", certFactory);
        }

        rootCertStream = FileUtils.openInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()));
        intermediateCertStream = FileUtils
                .openInputStream(FileUtils.getFile(certConfig.getIntermediateCertificateFile()));

        if (DEBUG) {
            DEBUGGER.debug("rootCertStream: {}", rootCertStream);
            DEBUGGER.debug("intermediateCertStream: {}", intermediateCertStream);
        }

        X509Certificate[] responseCert = new X509Certificate[] {
                (X509Certificate) certFactory.generateCertificate(rootCertStream),
                (X509Certificate) certFactory.generateCertificate(intermediateCertStream),
                (X509Certificate) certFactory.generateCertificate(certStream) };

        if (DEBUG) {
            DEBUGGER.debug("X509Certificate[]", (Object) responseCert);
        }

        storeStream = FileUtils.openOutputStream(keystoreFile);
        keyStore.setKeyEntry(commonName, privateKey, storePassword.toCharArray(), responseCert);
        keyStore.store(storeStream, storePassword.toCharArray());

        isComplete = true;
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } catch (UnrecoverableKeyException ukx) {
        throw new CertificateManagementException(ukx.getMessage(), ukx);
    } finally {
        if (storeStream != null) {
            IOUtils.closeQuietly(storeStream);
        }

        if (intermediateCertStream != null) {
            IOUtils.closeQuietly(intermediateCertStream);
        }

        if (rootCertStream != null) {
            IOUtils.closeQuietly(rootCertStream);
        }

        if (certStream != null) {
            IOUtils.closeQuietly(certStream);
        }

        if (keystoreInput != null) {
            IOUtils.closeQuietly(keystoreInput);
        }
    }

    return isComplete;
}

From source file:be.fedict.eid.tsl.TrustService.java

public X509Certificate getServiceDigitalIdentity(DigitalIdentityListType digitalIdentityList) {

    try {/*from   www.j ava 2 s  .  c  o m*/
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        for (final DigitalIdentityType digitalIdentity : digitalIdentityList.getDigitalId()) {
            byte[] x509CertificateData = digitalIdentity.getX509Certificate();
            if (x509CertificateData != null) {
                try {
                    X509Certificate certificate = (X509Certificate) certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateData));
                    return certificate;
                } catch (CertificateException e) {
                    throw new RuntimeException("X509 error: " + e.getMessage(), e);
                }
            }
        }
        throw new RuntimeException("No X509Certificate identity specified");
    } catch (CertificateException e) {
        throw new RuntimeException("X509 error: " + e.getMessage(), e);
    }
}