Example usage for java.security KeyStore store

List of usage examples for java.security KeyStore store

Introduction

In this page you can find the example usage for java.security KeyStore store.

Prototype

public final void store(OutputStream stream, char[] password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException 

Source Link

Document

Stores this keystore to the given output stream, and protects its integrity with the given password.

Usage

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

@Deprecated //Remove this method as soon as upgrading from 5.0->6.x is dropped
private void processSoftKeystore(AuthenticationToken authenticationToken, File file, String softStorePassword,
        String softKeyPassword, boolean doNotStorePasswordsInMemory,
        List<InternalKeyBindingTrustEntry> trustDefaults) {
    KeyStore keyStore;
    final char[] passwordChars = softStorePassword.toCharArray();
    // Load keystore (JKS or PKCS#12)
    try {//from   w  ww .  ja v  a2  s. c o  m
        keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(file), passwordChars);
    } catch (Exception e) {
        try {
            keyStore = KeyStore.getInstance("PKCS12", "BC");
            keyStore.load(new FileInputStream(file), passwordChars);
        } catch (Exception e2) {
            try {
                log.info("Unable to process " + file.getCanonicalPath() + " as a KeyStore.");
            } catch (IOException e3) {
                log.warn(e3.getMessage());
            }
            return;
        }
    }

    // Strip issuer certs, etc. and convert to PKCS#12
    try {
        keyStore = makeKeysOnlyP12(keyStore, passwordChars);
    } catch (Exception e) {
        throw new RuntimeException("failed to convert keystore to P12 during keybindings upgrade", e);
    }

    final String name = file.getName();
    if (cryptoTokenManagementSession.getIdFromName(name) != null) {
        return; // already upgraded
    }
    log.info(" Processing Soft KeyStore '" + name + "' of type " + keyStore.getType());
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // Save the store using the same password as the keys are protected with (not the store password)
        // so we don't have to replace the protection for each key
        keyStore.store(baos, softKeyPassword.toCharArray());
        final Properties cryptoTokenProperties = new Properties();
        if (!doNotStorePasswordsInMemory) {
            log.info(" Auto-activation will be used.");
            BaseCryptoToken.setAutoActivatePin(cryptoTokenProperties, new String(softKeyPassword), true);
        } else {
            log.info(" Auto-activation will not be used.");
        }
        final int softCryptoTokenId = cryptoTokenManagementSession.createCryptoToken(authenticationToken, name,
                SoftCryptoToken.class.getName(), cryptoTokenProperties, baos.toByteArray(),
                softKeyPassword.toCharArray());
        createInternalKeyBindings(authenticationToken, softCryptoTokenId, keyStore, trustDefaults);
    } catch (Exception e) {
        log.warn(e.getMessage());
    }
}

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();
        }//  w w  w .ja  va 2 s .  c  om

        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:mitm.application.djigzo.workflow.impl.KeyAndCertificateWorkflowImpl.java

private void getPFXTransacted(Collection<X509Certificate> certificates, char[] password, boolean includeRoot,
        OutputStream pfx) throws KeyStoreException {
    try {//from w ww  .j av  a 2 s .com
        KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

        keyStore.load(null);

        for (X509Certificate certificate : certificates) {
            if (certificate == null) {
                continue;
            }

            X509CertStoreEntry entry = keyAndCertStore.getByCertificate(certificate);

            if (entry != null && entry.getCertificate() != null) {
                KeyAndCertificate keyAndCertificate = keyAndCertStore.getKeyAndCertificate(entry);

                if (keyAndCertificate != null) {
                    if (!certificate.equals(keyAndCertificate.getCertificate())) {
                        throw new IllegalStateException("Certificate mismatch.");
                    }

                    X509Certificate[] chain = null;

                    /*
                     * Build a certificate chain so we add the chain (if valid)
                     */
                    try {
                        CertificatePathBuilder pathBuilder = pathBuilderFactory.createCertificatePathBuilder();

                        CertPathBuilderResult pathBuilderResult = pathBuilder.buildPath(certificate);

                        X509Certificate root = null;

                        if (includeRoot && pathBuilderResult instanceof PKIXCertPathBuilderResult) {
                            TrustAnchor trustAnchor = ((PKIXCertPathBuilderResult) pathBuilderResult)
                                    .getTrustAnchor();

                            if (trustAnchor != null) {
                                root = trustAnchor.getTrustedCert();
                            }
                        }

                        CertPath certPath = pathBuilderResult.getCertPath();

                        if (certPath != null && CollectionUtils.isNotEmpty(certPath.getCertificates())) {
                            List<X509Certificate> completePath = new LinkedList<X509Certificate>();

                            for (Certificate fromPath : certPath.getCertificates()) {
                                if (!(fromPath instanceof X509Certificate)) {
                                    /*
                                     * only X509Certificates are supported
                                     */
                                    continue;
                                }

                                completePath.add((X509Certificate) fromPath);
                            }

                            if (root != null && includeRoot) {
                                completePath.add(root);
                            }

                            chain = new X509Certificate[completePath.size()];

                            chain = completePath.toArray(chain);
                        }
                    } catch (CertPathBuilderException e) {
                        logger.warn(
                                "Could not build a path. Message: " + ExceptionUtils.getRootCauseMessage(e));
                    }

                    if (ArrayUtils.getLength(chain) == 0) {
                        chain = new X509Certificate[] { certificate };
                    }

                    String alias = X509CertificateInspector.getThumbprint(certificate);

                    if (keyAndCertificate.getPrivateKey() != null) {
                        keyStore.setKeyEntry(alias, keyAndCertificate.getPrivateKey(), password, chain);
                    } else {
                        keyStore.setCertificateEntry(alias, certificate);
                    }
                }
            }
        }

        keyStore.store(pfx, password);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreException(e);
    } catch (CertificateException e) {
        throw new KeyStoreException(e);
    } catch (IOException e) {
        throw new KeyStoreException(e);
    } catch (CertStoreException e) {
        throw new KeyStoreException(e);
    } catch (NoSuchProviderException e) {
        throw new NoSuchProviderRuntimeException(e);
    } catch (SecurityFactoryFactoryException e) {
        throw new KeyStoreException(e);
    }
}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Change the Keystore and the Truststore's master password to the one
 * provided. The Keystore and Truststore both use the same password.
 *//*from w ww.ja v  a  2 s .  co m*/
@Override
public void changeMasterPassword(String newMasterPassword) throws CMException {
    // Need to make sure we are initialized before we do anything else
    // as Credential Manager can be created but not initialized
    initialize();

    String oldMasterPassword = masterPassword;
    KeyStore oldKeystore = keystore;
    KeyStore oldTruststore = truststore;

    try {
        synchronized (keystore) {
            // Create a new keystore and copy all items from the current
            // one, encrypting them with the new password
            KeyStore newKeystore = null;
            try {
                // Try to create Taverna's Keystore as Bouncy Castle
                // UBER-type keystore.
                newKeystore = KeyStore.getInstance("UBER", "BC");
            } catch (Exception ex) {
                // The requested keystore type is not available from
                // security providers.
                String exMessage = "Failed to instantiate a new Bouncy Castle Keystore when changing master password.";
                throw new CMException(exMessage, ex);
            }
            try {
                // Initialize a new empty keystore
                newKeystore.load(null, null);
            } catch (Exception ex) {
                String exMessage = "Failed to create a new empty Keystore to copy over the entries from the current one.";
                throw new CMException(exMessage, ex);
            }

            Enumeration<String> aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (REALLY_DISABLED) {
                    if (alias.startsWith("password#")) { // a password entry
                        SecretKeySpec passwordKey = (((SecretKeySpec) keystore.getKey(alias,
                                masterPassword.toCharArray())));
                        newKeystore.setKeyEntry(alias, passwordKey, newMasterPassword.toCharArray(), null);
                    } else if (alias.startsWith("keypair#")) { // a private key entry
                        // Get the private key for the alias
                        PrivateKey privateKey = (PrivateKey) keystore.getKey(alias,
                                masterPassword.toCharArray());
                        // Get the related public key's certificate chain
                        Certificate[] certChain = keystore.getCertificateChain(alias);
                        newKeystore.setKeyEntry(alias, privateKey, newMasterPassword.toCharArray(), certChain);
                    }
                }
                // Do all entries at once, not reason to separate password &
                // key pair entries
                newKeystore.setEntry(alias,
                        keystore.getEntry(alias, new KeyStore.PasswordProtection(masterPassword.toCharArray())),
                        new KeyStore.PasswordProtection(newMasterPassword.toCharArray()));
            }
            try (FileOutputStream fos = new FileOutputStream(keystoreFile)) {
                newKeystore.store(fos, newMasterPassword.toCharArray());
            }
            keystore = newKeystore;
        }

        // Truststore does not need to be re-encrypeted item by item as
        // entries there are not encrypted, just the whole truststore
        synchronized (truststore) {
            try (FileOutputStream fos = new FileOutputStream(truststoreFile)) {
                truststore.store(fos, newMasterPassword.toCharArray());
            }
        }

        // Set the new master password as well
        masterPassword = newMasterPassword;
    } catch (Exception ex) {
        // rollback
        keystore = oldKeystore;
        truststore = oldTruststore;
        masterPassword = oldMasterPassword;
        saveKeystore(KEYSTORE);
        saveKeystore(TRUSTSTORE);

        String exMessage = "Failed to change maaster password - reverting to the old one";
        logger.error(exMessage, ex);
        throw (new CMException(exMessage));
    }
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public byte[] exportCAKeyStore(AuthenticationToken admin, String caname, String keystorepass,
        String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) {
    log.trace(">exportCAKeyStore");
    try {/*ww  w  .  j  a va 2 s  .c o m*/
        final CA thisCa = caSession.getCAForEdit(admin, caname);
        // Make sure we are not trying to export a hard or invalid token
        CAToken thisCAToken = thisCa.getCAToken();
        final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId());
        if (!(cryptoToken instanceof SoftCryptoToken)) {
            throw new IllegalCryptoTokenException("Cannot export anything but a soft token.");
        }
        // Do not allow export without password protection
        if (StringUtils.isEmpty(keystorepass) || StringUtils.isEmpty(privkeypass)) {
            throw new IllegalArgumentException("Cannot export a token without password protection.");
        }
        // Check authorization
        if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) {
            String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoexportcatoken", caname);
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details);
            throw new AuthorizationDeniedException(msg);
        }
        // Fetch keys
        final char[] password = keystorepass.toCharArray();
        ((SoftCryptoToken) cryptoToken).checkPasswordBeforeExport(password);
        cryptoToken.activate(password);

        PrivateKey p12PrivateEncryptionKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT));
        PublicKey p12PublicEncryptionKey = cryptoToken
                .getPublicKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT));
        PrivateKey p12PrivateCertSignKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));
        PrivateKey p12PrivateCRLSignKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN));
        if (!p12PrivateCertSignKey.equals(p12PrivateCRLSignKey)) {
            throw new Exception("Assertion of equal signature keys failed.");
        }
        // Proceed with the export
        byte[] ret = null;
        String format = null;
        if (thisCa.getCAType() == CAInfo.CATYPE_CVC) {
            log.debug("Exporting private key with algorithm: " + p12PrivateCertSignKey.getAlgorithm()
                    + " of format: " + p12PrivateCertSignKey.getFormat());
            format = p12PrivateCertSignKey.getFormat();
            ret = p12PrivateCertSignKey.getEncoded();
        } else {
            log.debug("Exporting PKCS12 keystore");
            format = "PKCS12";
            KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
            keystore.load(null, keystorepass.toCharArray());
            // Load keys into keystore
            Certificate[] certificateChainSignature = (Certificate[]) thisCa.getCertificateChain()
                    .toArray(new Certificate[0]);
            Certificate[] certificateChainEncryption = new Certificate[1];
            // certificateChainSignature[0].getSigAlgName(),
            // generate dummy certificate for encryption key.
            certificateChainEncryption[0] = CertTools.genSelfCertForPurpose("CN=dummy2", 36500, null,
                    p12PrivateEncryptionKey, p12PublicEncryptionKey, thisCAToken.getEncryptionAlgorithm(), true,
                    X509KeyUsage.keyEncipherment, true);
            log.debug("Exporting with sigAlgorithm "
                    + AlgorithmTools.getSignatureAlgorithm(certificateChainSignature[0]) + "encAlgorithm="
                    + thisCAToken.getEncryptionAlgorithm());
            if (keystore.isKeyEntry(privateSignatureKeyAlias)) {
                throw new Exception("Key \"" + privateSignatureKeyAlias + "\"already exists in keystore.");
            }
            if (keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                throw new Exception("Key \"" + privateEncryptionKeyAlias + "\"already exists in keystore.");
            }

            keystore.setKeyEntry(privateSignatureKeyAlias, p12PrivateCertSignKey, privkeypass.toCharArray(),
                    certificateChainSignature);
            keystore.setKeyEntry(privateEncryptionKeyAlias, p12PrivateEncryptionKey, privkeypass.toCharArray(),
                    certificateChainEncryption);
            // Return KeyStore as byte array and clean up
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            keystore.store(baos, keystorepass.toCharArray());
            if (keystore.isKeyEntry(privateSignatureKeyAlias)) {
                keystore.deleteEntry(privateSignatureKeyAlias);
            }
            if (keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                keystore.deleteEntry(privateEncryptionKeyAlias);
            }
            ret = baos.toByteArray();
        }
        String msg = intres.getLocalizedMessage("caadmin.exportedca", caname, format);
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details);
        log.trace("<exportCAKeyStore");
        return ret;
    } catch (Exception e) {
        String msg = intres.getLocalizedMessage("caadmin.errorexportca", caname, "PKCS12", e.getMessage());
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), null, null, null, details);
        throw new EJBException(e);
    }
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Change the Keystore and the Truststore's master password to the one
 * provided. The Keystore and Truststore both use the same password.
 *///from   w w w. ja  v a2s  .co  m
@Override
public void changeMasterPassword(String newMasterPassword) throws CMException {
    /*
     * Need to make sure we are initialized before we do anything else, as
     * the Credential Manager can be created but not initialized.
     */
    initialize();

    String oldMasterPassword = masterPassword;
    KeyStore oldKeystore = keystore;
    KeyStore oldTruststore = truststore;

    try {
        synchronized (keystore) {
            // Create a new keystore and copy all items from the current
            // one, encrypting them with the new password
            KeyStore newKeystore = null;
            try {
                // Try to create Taverna's Keystore as Bouncy Castle
                // UBER-type keystore.
                newKeystore = KeyStore.getInstance("UBER", "BC");
            } catch (Exception ex) {
                // The requested keystore type is not available from
                // security providers.
                String exMessage = "Failed to instantiate a new Bouncy Castle Keystore when changing master password.";
                throw new CMException(exMessage, ex);
            }
            try {
                // Initialize a new empty keystore
                newKeystore.load(null, null);
            } catch (Exception ex) {
                String exMessage = "Failed to create a new empty Keystore to copy over the entries from the current one.";
                throw new CMException(exMessage, ex);
            }

            Enumeration<String> aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (REALLY_DISABLED) {
                    if (alias.startsWith("password#")) { // a password entry
                        SecretKeySpec passwordKey = (((SecretKeySpec) keystore.getKey(alias,
                                masterPassword.toCharArray())));
                        newKeystore.setKeyEntry(alias, passwordKey, newMasterPassword.toCharArray(), null);
                    } else if (alias.startsWith("keypair#")) { // a private key entry
                        // Get the private key for the alias
                        PrivateKey privateKey = (PrivateKey) keystore.getKey(alias,
                                masterPassword.toCharArray());
                        // Get the related public key's certificate chain
                        Certificate[] certChain = keystore.getCertificateChain(alias);
                        newKeystore.setKeyEntry(alias, privateKey, newMasterPassword.toCharArray(), certChain);
                    }
                }
                /*
                 * Do all entries at once, not reason to separate password &
                 * key pair entries
                 */
                newKeystore.setEntry(alias,
                        keystore.getEntry(alias, new KeyStore.PasswordProtection(masterPassword.toCharArray())),
                        new KeyStore.PasswordProtection(newMasterPassword.toCharArray()));
            }
            try (FileOutputStream fos = new FileOutputStream(keystoreFile)) {
                newKeystore.store(fos, newMasterPassword.toCharArray());
            }
            keystore = newKeystore;
        }

        /*
         * Truststore does not need to be re-encrypeted item by item as
         * entries there are not encrypted, just the whole truststore
         */
        synchronized (truststore) {
            try (FileOutputStream fos = new FileOutputStream(truststoreFile)) {
                truststore.store(fos, newMasterPassword.toCharArray());
            }
        }

        // Set the new master password as well
        masterPassword = newMasterPassword;
    } catch (Exception ex) {
        // rollback
        keystore = oldKeystore;
        truststore = oldTruststore;
        masterPassword = oldMasterPassword;
        saveKeystore(KEYSTORE);
        saveKeystore(TRUSTSTORE);

        String exMessage = "Failed to change maaster password - reverting to the old one";
        logger.error(exMessage, ex);
        throw new CMException(exMessage);
    }
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

/**
 * Method that import CA token keys from a P12 file. Was originally used when upgrading from old EJBCA versions. Only supports SHA1 and SHA256
 * with RSA or ECDSA and SHA1 with DSA./*www .  jav  a 2  s . co  m*/
 * @throws OperatorCreationException 
 * @throws AuthorizationDeniedException 
 */
private CAToken importKeysToCAToken(AuthenticationToken authenticationToken, String authenticationCode,
        Properties caTokenProperties, PrivateKey privatekey, PublicKey publickey,
        PrivateKey privateEncryptionKey, PublicKey publicEncryptionKey, Certificate[] caSignatureCertChain,
        int caId) throws CryptoTokenAuthenticationFailedException, IllegalCryptoTokenException,
        OperatorCreationException, AuthorizationDeniedException {
    // If we don't give an authentication code, perhaps we have autoactivation enabled
    if (StringUtils.isEmpty(authenticationCode)) {
        String msg = intres.getLocalizedMessage("token.authcodemissing", Integer.valueOf(caId));
        log.info(msg);
        throw new CryptoTokenAuthenticationFailedException(msg);
    }
    if (caTokenProperties == null) {
        caTokenProperties = new Properties();
    }

    try {
        // Currently only RSA keys are supported
        KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(null, null);

        // The CAs certificate is first in chain
        Certificate cacert = caSignatureCertChain[0];
        // Assume that the same hash algorithm is used for signing that was used to sign this CA cert
        String signatureAlgorithm = AlgorithmTools.getSignatureAlgorithm(cacert);
        String keyAlg = AlgorithmTools.getKeyAlgorithm(publickey);
        if (keyAlg == null) {
            throw new IllegalCryptoTokenException(
                    "Unknown public key type: " + publickey.getAlgorithm() + " (" + publickey.getClass() + ")");
        }

        // import sign keys.
        final Certificate[] certchain = new Certificate[1];
        certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, privatekey, publickey, signatureAlgorithm,
                true);

        keystore.setKeyEntry(CAToken.SOFTPRIVATESIGNKEYALIAS, privatekey, null, certchain);

        // generate enc keys.
        // Encryption keys must be RSA still
        final String encryptionAlgorithm = AlgorithmTools.getEncSigAlgFromSigAlg(signatureAlgorithm);
        keyAlg = AlgorithmTools.getKeyAlgorithmFromSigAlg(encryptionAlgorithm);
        final String enckeyspec = "2048";
        KeyPair enckeys = null;
        if (publicEncryptionKey == null || privateEncryptionKey == null) {
            enckeys = KeyTools.genKeys(enckeyspec, keyAlg);
        } else {
            enckeys = new KeyPair(publicEncryptionKey, privateEncryptionKey);
        }
        // generate dummy certificate
        certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, enckeys.getPrivate(),
                enckeys.getPublic(), encryptionAlgorithm, true);
        keystore.setKeyEntry(CAToken.SOFTPRIVATEDECKEYALIAS, enckeys.getPrivate(), null, certchain);

        // Set the token properties
        caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING,
                CAToken.SOFTPRIVATESIGNKEYALIAS);
        caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING,
                CAToken.SOFTPRIVATESIGNKEYALIAS);
        caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING,
                CAToken.SOFTPRIVATEDECKEYALIAS);

        // Write the keystore to byte[] that we can feed to crypto token factory
        final char[] authCode = authenticationCode.toCharArray();
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        keystore.store(baos, authCode);

        // Now we have the PKCS12 keystore, from this we can create the CAToken
        final Properties cryptoTokenProperties = new Properties();
        int cryptoTokenId;
        try {
            cryptoTokenId = createCryptoTokenWithUniqueName(authenticationToken, "ImportedCryptoToken" + caId,
                    SoftCryptoToken.class.getName(), cryptoTokenProperties, baos.toByteArray(), authCode);
        } catch (NoSuchSlotException e1) {
            throw new RuntimeException(
                    "Attempte to define a slot for a soft crypto token. This should not happen.");
        }
        final CAToken catoken = new CAToken(cryptoTokenId, caTokenProperties);
        // If this is a CVC CA we need to find out the sequence
        String sequence = CAToken.DEFAULT_KEYSEQUENCE;
        if (cacert instanceof CardVerifiableCertificate) {
            CardVerifiableCertificate cvccacert = (CardVerifiableCertificate) cacert;
            log.debug("Getting sequence from holderRef in CV certificate.");
            try {
                sequence = cvccacert.getCVCertificate().getCertificateBody().getHolderReference().getSequence();
            } catch (NoSuchFieldException e) {
                log.error("Can not get sequence from holderRef in CV certificate, using default sequence.");
            }
        }
        log.debug("Setting sequence " + sequence);
        catoken.setKeySequence(sequence);
        log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
        catoken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
        catoken.setSignatureAlgorithm(signatureAlgorithm);
        catoken.setEncryptionAlgorithm(encryptionAlgorithm);
        return catoken;
    } catch (KeyStoreException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (NoSuchProviderException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (CertificateException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (IOException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (IllegalStateException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (CryptoTokenOfflineException e) {
        throw new IllegalCryptoTokenException(e);
    }
}

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

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int)
 *///from ww  w.  jav a 2 s.com
public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword,
        final int validityPeriod, final int keySize) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", subjectData);
        DEBUGGER.debug("Value: {}", validityPeriod);
        DEBUGGER.debug("Value: {}", keySize);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final String signatureAlgorithm = certConfig.getSignatureAlgorithm();
    final String certificateAlgorithm = certConfig.getCertificateAlgorithm();
    final File privateKeyDirectory = FileUtils
            .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0));
    final File publicKeyDirectory = FileUtils
            .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0));
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0));
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0));
    final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O="
            + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C="
            + subjectData.get(5) + ",E=" + subjectData.get(6));

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm);
        DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm);
        DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory);
        DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("x500Name: {}", x500Name);
    }

    File csrFile = null;
    JcaPEMWriter csrPemWriter = null;
    JcaPEMWriter publicKeyWriter = null;
    JcaPEMWriter privateKeyWriter = null;
    FileOutputStream csrFileStream = null;
    FileOutputStream keyStoreStream = null;
    FileOutputStream publicKeyFileStream = null;
    FileOutputStream privateKeyFileStream = null;
    OutputStreamWriter csrFileStreamWriter = null;
    OutputStreamWriter privateKeyStreamWriter = null;
    OutputStreamWriter publicKeyStreamWriter = null;

    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, storePassword.toCharArray());

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

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm);
        keyGenerator.initialize(keySize, random);

        if (DEBUG) {
            DEBUGGER.debug("KeyGenerator: {}", keyGenerator);
        }

        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (DEBUG) {
            DEBUGGER.debug("KeyPair: {}", keyPair);
        }

        if (keyPair != null) {
            final Signature sig = Signature.getInstance(signatureAlgorithm);
            final PrivateKey privateKey = keyPair.getPrivate();
            final PublicKey publicKey = keyPair.getPublic();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
                DEBUGGER.debug("PrivateKey: {}", privateKey);
                DEBUGGER.debug("PublicKey: {}", publicKey);
            }

            sig.initSign(privateKey, random);
            ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);

            if (DEBUG) {
                DEBUGGER.debug("ContentSigner: {}", signGen);
            }

            Calendar expiry = Calendar.getInstance();
            expiry.add(Calendar.DAY_OF_YEAR, validityPeriod);

            if (DEBUG) {
                DEBUGGER.debug("Calendar: {}", expiry);
            }

            CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

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

            X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory
                    .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) };

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

            keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate(
                    new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()))));
            keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(),
                    certFactory.generateCertificate(new FileInputStream(
                            FileUtils.getFile(certConfig.getIntermediateCertificateFile()))));

            PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
                    publicKey);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder);
            }

            PKCS10CertificationRequest csr = builder.build(signGen);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequest: {}", csr);
            }

            // write private key
            File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

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

            if (!(privateKeyFile.createNewFile())) {
                throw new IOException("Failed to store private file");
            }

            privateKeyFileStream = new FileOutputStream(privateKeyFile);
            privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream);
                DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter);
            }

            privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter);
            privateKeyWriter.writeObject(privateKey);
            privateKeyWriter.flush();
            privateKeyStreamWriter.flush();
            privateKeyFileStream.flush();

            // write public key
            File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

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

            if (!(publicKeyFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            publicKeyFileStream = new FileOutputStream(publicKeyFile);
            publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter);
            publicKeyWriter.writeObject(publicKey);
            publicKeyWriter.flush();
            publicKeyStreamWriter.flush();
            publicKeyFileStream.flush();

            // write csr
            csrFile = FileUtils
                    .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT);

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

            if (!(csrFile.createNewFile())) {
                throw new IOException("Failed to store CSR file");
            }

            csrFileStream = new FileOutputStream(csrFile);
            csrFileStreamWriter = new OutputStreamWriter(csrFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            csrPemWriter = new JcaPEMWriter(csrFileStreamWriter);
            csrPemWriter.writeObject(csr);
            csrPemWriter.flush();
            csrFileStreamWriter.flush();
            csrFileStream.flush();

            File keyStoreFile = FileUtils
                    .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType());

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

            keyStoreStream = FileUtils.openOutputStream(keyStoreFile);

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

            keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(),
                    issuerCert);
            keyStore.store(keyStoreStream, storePassword.toCharArray());
            keyStoreStream.flush();

            if (DEBUG) {
                DEBUGGER.debug("KeyStore: {}", keyStore);
            }
        } else {
            throw new CertificateManagementException("Failed to generate keypair. Cannot continue.");
        }
    } 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 (InvalidKeyException ikx) {
        throw new CertificateManagementException(ikx.getMessage(), ikx);
    } catch (OperatorCreationException ocx) {
        throw new CertificateManagementException(ocx.getMessage(), ocx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } finally {
        if (csrFileStreamWriter != null) {
            IOUtils.closeQuietly(csrFileStreamWriter);
        }

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

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

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

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

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

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

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

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

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

    return csrFile;
}