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.keys.token.CryptoTokenManagementSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override//  w w  w.  ja  v a  2s .co m
public boolean updatePin(AuthenticationToken authenticationToken, Integer cryptoTokenId,
        char[] currentAuthenticationCode, char[] newAuthenticationCode, boolean updateOnly)
        throws AuthorizationDeniedException, CryptoTokenAuthenticationFailedException,
        CryptoTokenOfflineException {
    final String[] requiredAuthorization = new String[] {
            CryptoTokenRules.MODIFY_CRYPTOTOKEN.resource() + "/" + cryptoTokenId,
            CryptoTokenRules.ACTIVATE.resource() + "/" + cryptoTokenId,
            CryptoTokenRules.DEACTIVATE.resource() + "/" + cryptoTokenId };
    if (!accessControlSessionSession.isAuthorized(authenticationToken, requiredAuthorization)) {
        final String msg = INTRES.getLocalizedMessage("authorization.notuathorizedtoresource",
                Arrays.toString(requiredAuthorization), authenticationToken.toString());
        throw new AuthorizationDeniedException(msg);
    }
    CryptoToken cryptoToken = getCryptoToken(cryptoTokenId);
    final Properties cryptoTokenProperties = cryptoToken.getProperties();
    // Get current auto-activation pin (if any)
    final String oldAutoActivationPin = BaseCryptoToken.getAutoActivatePin(cryptoTokenProperties);
    if (oldAutoActivationPin == null && (updateOnly || newAuthenticationCode == null)) {
        // This is a NOOP call that will not lead to any change
        return false;
    }
    if (SoftCryptoToken.class.getName().equals(cryptoToken.getClass().getName())) {
        CryptoProviderTools.installBCProviderIfNotAvailable();
        final KeyStore keystore;
        try {
            keystore = KeyStore.getInstance("PKCS12", "BC");
            keystore.load(new ByteArrayInputStream(cryptoToken.getTokenData()), currentAuthenticationCode);
        } catch (Exception e) {
            final String msg = "Failed to use supplied current PIN." + " " + e;
            log.info(msg);
            throw new CryptoTokenAuthenticationFailedException(msg);
        }
        if (newAuthenticationCode == null) {
            // When no new pin is supplied, we will not modify the key-store and just remove the current auto-activation pin
            cryptoTokenProperties.remove(CryptoToken.AUTOACTIVATE_PIN_PROPERTY);
            cryptoToken.setProperties(cryptoTokenProperties);
        } else {
            try {
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                keystore.store(baos, newAuthenticationCode);
                baos.close();
                if (oldAutoActivationPin != null || !updateOnly) {
                    BaseCryptoToken.setAutoActivatePin(cryptoTokenProperties, new String(newAuthenticationCode),
                            true);
                } else {
                    log.debug(
                            "Auto-activation will not be used. Only changing pin for soft CryptoToken keystore.");
                }
                cryptoToken = CryptoTokenFactory.createCryptoToken(SoftCryptoToken.class.getName(),
                        cryptoTokenProperties, baos.toByteArray(), cryptoTokenId, cryptoToken.getTokenName());
            } catch (Exception e) {
                log.info("Unable to store soft keystore with new PIN: " + e);
                throw new CryptoTokenAuthenticationFailedException(
                        "Unable to store soft keystore with new PIN");
            }
        }
    } else {
        if (oldAutoActivationPin != null) {
            // If we have an old auto-activation pin we will compare the "current" with this value to avoid deactivating the token
            if (!oldAutoActivationPin.equals(new String(currentAuthenticationCode))) {
                final String msg = "Supplied PIN did not match auto-activation PIN.";
                log.info(msg);
                throw new CryptoTokenAuthenticationFailedException(msg);
            } else {
                log.debug(
                        "Successfully verified the PIN for non-soft CryptoToken by comparing supplied PIN to auto-activation PIN.");
            }
        } else {
            // If we don't have an auto-activation pin to compare the supplied PIN to, we need to verify the supplied
            // PIN can be used in a de-activation/activation cycle.
            final boolean wasInactive = !isCryptoTokenStatusActive(authenticationToken, cryptoTokenId);
            cryptoToken.deactivate();
            cryptoToken.activate(currentAuthenticationCode);
            if (wasInactive) {
                // Note that there is a small glitch here where the token was active, but we have no other options to verify the pin
                cryptoToken.deactivate();
            }
        }
        if (newAuthenticationCode == null) {
            cryptoTokenProperties.remove(CryptoToken.AUTOACTIVATE_PIN_PROPERTY);
        } else {
            BaseCryptoToken.setAutoActivatePin(cryptoTokenProperties, new String(newAuthenticationCode), true);
        }
        cryptoToken.setProperties(cryptoTokenProperties);
    }
    // Save the modified CryptoToken
    try {
        cryptoTokenSession.mergeCryptoToken(cryptoToken);
    } catch (CryptoTokenNameInUseException e) {
        // This should not happen here since we use the same name and id
        throw new RuntimeException(e);
    }
    securityEventsLoggerSession.log(EventTypes.CRYPTOTOKEN_UPDATEPIN, EventStatus.SUCCESS,
            ModuleTypes.CRYPTOTOKEN, ServiceTypes.CORE, authenticationToken.toString(),
            String.valueOf(cryptoTokenId), null, null,
            "Updated PIN of CryptoToken '" + cryptoToken.getTokenName() + "' with id " + cryptoTokenId);
    // Return the current auto-activation state
    return BaseCryptoToken.getAutoActivatePin(cryptoTokenProperties) != null;
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;/*from   w w w. ja  va 2 s  .  c o m*/
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.error(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}

From source file:org.eclipse.gyrex.admin.ui.http.jetty.internal.ImportCertificateDialog.java

void importKeystore(final InputStream in) throws Exception {
    KeyStore tempKs;//from  w w  w  .  j  a v  a 2s. c o  m
    if (keystoreTypeField.isSelected(0)) {
        tempKs = KeyStore.getInstance("JKS");
    } else if (keystoreTypeField.isSelected(1)) {
        tempKs = KeyStore.getInstance("PKCS12");
    } else {
        throw new IllegalArgumentException(
                "Please select a keystore type before uploading a keystore and retry.");
    }

    final String keystorePassword = keyStorePasswordField.getText();
    final String keyPassword = keyPasswordField.getText();

    // load keystore
    tempKs.load(new BufferedInputStream(in), null != keystorePassword ? keystorePassword.toCharArray() : null);

    // initialize new JKS store
    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);

    generatedKeystorePassword = UUID.randomUUID().toString().toCharArray();
    generatedKeyPassword = UUID.randomUUID().toString().toCharArray();

    // verify and copy into new store
    final Enumeration aliases = tempKs.aliases();
    while (aliases.hasMoreElements()) {
        final String alias = (String) aliases.nextElement();
        if (tempKs.isKeyEntry(alias)) {
            final Key key = tempKs.getKey(alias, null != keyPassword ? keyPassword.toCharArray()
                    : null != keystorePassword ? keystorePassword.toCharArray() : null);
            Certificate[] chain = tempKs.getCertificateChain(alias);
            if (null == chain) {
                final Certificate certificate = tempKs.getCertificate(alias);
                if (null == certificate) {
                    // skip to next
                    continue;
                }
                chain = new Certificate[] { certificate };
            }
            ks.setKeyEntry("jetty", key, generatedKeyPassword, chain);
            break;
        }
    }

    if (!ks.aliases().hasMoreElements()) {
        throw new IllegalArgumentException(
                "The uploaded keystore does not have a valid key + certificate chain entry. Please use a different keystore and retry.");
    }

    // write into bytes
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    ks.store(out, generatedKeystorePassword);

    keystoreBytes = out.toByteArray();
}

From source file:org.mule.transport.ldap.util.DSManager.java

public synchronized void start(final boolean allowAnon) throws Exception {
    if (running) {

        logger.debug("start() called while already running");

        if (checkSocketNotConnected()) {
            logger.debug("start() forced");
        } else {//ww  w  .  j  ava 2s.  c  om
            logger.debug("DS is already running, stop it, then start it.");

            try {
                stop();

            } catch (final Exception e) {
                // TODO: handle exception
            }

            // throw new IllegalStateException("DS already running on port "
            // + port);
        }

    }

    logger.debug("DS is starting ...");

    port = 10389;

    directoryService = new DefaultDirectoryService();
    directoryService.setShutdownHookEnabled(false);
    // directoryService.getChangeLog().setEnabled(true);
    directoryService.setAllowAnonymousAccess(allowAnon);

    socketAcceptor = new SocketAcceptor(null);
    ldapService = new LdapService();
    ldapService.setSocketAcceptor(socketAcceptor);
    ldapService.setDirectoryService(directoryService);
    ldapService.setIpPort(port);
    // ldapService.setIpAddress("gkar.kerb.de");

    // ldapService.setAccessControlEnabled(false);
    // ldapService.setShutdownHookEnabled(false);
    ldapService.setAllowAnonymousAccess(allowAnon);

    // ldapService.getLdapsConfiguration().setIpPort(10636);
    // ldapService.getLdapsConfiguration().setEnabled(true);
    // ldapService.getLdapsConfiguration().setLdapsCertificateFile(new
    // File("src/test/resources/ldaps-server-cert.jks"));
    // ldapService.getLdapsConfiguration().setIpPort(10636);

    setupSaslMechanisms(ldapService);

    // S
    ldapSService = new LdapService();
    ldapSService.setSocketAcceptor(socketAcceptor);
    ldapSService.setDirectoryService(directoryService);
    ldapSService.setIpPort(10636);
    ldapSService.setEnableLdaps(true);

    setupSaslMechanisms(ldapSService);

    // ldapSService.setConfidentialityRequired(true);
    ldapSService.setConfidentialityRequired(true);
    // ldapService.setIpAddress("gkar.kerb.de");

    // ldapService.setAccessControlEnabled(false);
    // ldapService.setShutdownHookEnabled(false);
    ldapSService.setAllowAnonymousAccess(allowAnon);

    // ldapService.getLdapsConfiguration().setIpPort(10636);
    // ldapService.getLdapsConfiguration().setEnabled(true);
    // ldapService.getLdapsConfiguration().setLdapsCertificateFile(new
    // File("src/test/resources/ldaps-server-cert.jks"));
    // ldapService.getLdapsConfiguration().setIpPort(10636);

    setupSaslMechanisms(ldapSService);

    doDelete(directoryService.getWorkingDirectory());

    directoryService.startup();

    // java.security.cert.X509Certificate cert =
    // TlsKeyGenerator.getCertificate(directoryService.getAdminSession().lookup(new
    // LdapDN("uid=admin,ou=system")).getOriginalEntry());

    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream("src/test/resources/truststore_2.jks"), "changeit".toCharArray());

    // java.security.cert.X509Certificate testcert =
    // (java.security.cert.X509Certificate) ks.getCertificate("test");
    // logger.debug(testcert);
    // directoryService.getAdminSession().lookup(new
    // LdapDN("uid=admin,ou=system")).getOriginalEntry().put("userCertificate",testcert.getEncoded());

    // logger.debug("type: "+testcert.getType());
    final java.security.cert.X509Certificate cert = TlsKeyGenerator.getCertificate(
            directoryService.getAdminSession().lookup(new LdapDN("uid=admin,ou=system")).getOriginalEntry());

    ks.setCertificateEntry("apachetmp", cert);

    final File tmpKs = new File("target/truststore_tmp.jks");
    if (tmpKs.exists()) {
        boolean del = tmpKs.delete();

        if (!del) {
            logger.error("Unable to delete " + tmpKs.getAbsolutePath());
            // throw new Exception("Unable to delete
            // "+tmpKs.getAbsolutePath());
        }
    }

    ks.store(new FileOutputStream("target/truststore_tmp.jks"), "changeit".toCharArray());

    logger.debug(cert);

    // TODO shouldn't this be before calling configureLdapServer() ???
    ldapService.addExtendedOperationHandler(new StartTlsHandler());
    ldapService.addExtendedOperationHandler(new StoredProcedureExtendedOperationHandler());

    ldapService.start();

    ldapSService.addExtendedOperationHandler(new StartTlsHandler());
    // ldapSService.add( new LdapsInitializer() );
    ldapSService.addExtendedOperationHandler(new StoredProcedureExtendedOperationHandler());

    ldapSService.start();

    // dn: uid=admin,ou=system
    setContexts(ServerDNConstants.ADMIN_SYSTEM_DN, "secret");

    setUpPartition();

    importLdif(IOUtils.getResourceAsStream("examplecom.ldif", this.getClass()));

    final Attributes attrs = new BasicAttributes();
    attrs.put(new BasicAttribute("userCertificate", ""));

    // sysRoot.modifyAttributes("uid=admin",LdapContext.REPLACE_ATTRIBUTE,attrs);
    logger.debug(rootDSE.getAuthenticatedPrincipal());
    logger.debug(rootDSE.getAuthenticationLevel());
    logger.debug(rootDSE.getEffectivePrincipal());
    logger.debug(rootDSE.toString());

    running = true;

    logger.debug("DS now started!");
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private boolean verifyCertificate(X509Certificate cert) {
    try {/*from  w  w w .j a va2  s.c  om*/
        String keypass = "";
        String keystorename = System.getProperty("deployment.user.security.trusted.certs");
        if (keystorename == null) {
            throw new IOException("No trusted certs keystore");
        }

        KeyStore keystore = KeyStore.getInstance("JKS", "SUN");
        File file = new File(keystorename);
        if (!file.exists()) {
            keystore.load(null, keypass.toCharArray());
        } else {
            keystore.load(new FileInputStream(keystorename), keypass.toCharArray());
        }
        boolean isInStore = false;
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements() && !isInStore) {
            String alias = aliases.nextElement();
            Certificate certificate = keystore.getCertificate(alias);
            if (certificate != null) {
                if (certificate.equals(cert)) {
                    isInStore = true;
                }
            }
        }
        if (!isInStore) {
            int result = JOptionPane.showConfirmDialog(null,
                    "Do you want to trust the bridge implementation " + "signed by\n"
                            + cert.getSubjectX500Principal().getName(),
                    "Trust source?", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                keystore.setEntry("deploymentusercert-" + System.currentTimeMillis(),
                        new KeyStore.TrustedCertificateEntry(cert), null);
                FileOutputStream output = new FileOutputStream(keystorename);
                keystore.store(output, keypass.toCharArray());
                output.close();
                return true;
            }
            return false;
        }
        return true;
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return false;
}

From source file:org.texai.x509.X509Utils.java

/** Creates the Texai root X.509 certificate keystore on the trusted development system.  This
 * keystore also includes a jar-signing certificate.
 *///from   w w w  . ja  va 2 s.com
protected static synchronized void createTexaiRootKeyStore() {
    //Preconditions
    assert !isTrustedDevelopmentSystem() || X509Utils.isJCEUnlimitedStrengthPolicy();

    if (!isTrustedDevelopmentSystem()) {
        return;
    }
    final char[] keyStorePassword = getRootKeyStorePassword();
    assert keyStorePassword != null;
    final String filePath = System.getenv("SECURITY_DIR") + "/texai-keystore.jceks";
    final File serverKeyStoreFile = new File(filePath);
    if (serverKeyStoreFile.exists()) {
        // do not overwrite it
        return;
    }
    try {
        LOGGER.info("creating Texai root key pair");
        final KeyPair rootKeyPair = generateRSAKeyPair3072();
        LOGGER.info("creating Texai root X.509 certificate");
        final X509Certificate rootX509Certificate = generateRootX509Certificate(rootKeyPair);
        LOGGER.info("root certificate...\n" + rootX509Certificate);
        final StringBuilder stringBuilder = new StringBuilder();
        for (final byte b : rootX509Certificate.getEncoded()) {
            stringBuilder.append(Byte.toString(b));
            stringBuilder.append(", ");
        }
        LOGGER.info("root certificate...\n" + rootX509Certificate);
        LOGGER.info("\nroot certificate bytes...\n" + stringBuilder.toString());
        LOGGER.info("creating Texai root X.509 certificate keystore");
        final KeyStore rootKeyStore = X509Utils.findOrCreateJceksKeyStore(filePath, keyStorePassword);
        rootKeyStore.setKeyEntry(ROOT_ALIAS, rootKeyPair.getPrivate(), keyStorePassword,
                new Certificate[] { rootX509Certificate });

        // create and store the jar-signer certificate
        LOGGER.info("creating jar-signer key pair");
        final KeyPair jarSignerKeyPair = generateRSAKeyPair2048();
        LOGGER.info("creating jar-signer X.509 certificate");
        final UUID jarSignerUUID = UUID.randomUUID();
        LOGGER.info("jar-signer UUID: " + jarSignerUUID);
        final X509Certificate jarSignerX509Certificate = generateX509Certificate(jarSignerKeyPair.getPublic(),
                rootKeyPair.getPrivate(), rootX509Certificate, jarSignerUUID, "RootCertificate"); // domainComponent
        LOGGER.info("jar-signer certificate:\n" + jarSignerX509Certificate);
        rootKeyStore.setKeyEntry(JAR_SIGNER_ALIAS, jarSignerKeyPair.getPrivate(), keyStorePassword,
                new Certificate[] { jarSignerX509Certificate, rootX509Certificate });
        rootKeyStore.store(new FileOutputStream(filePath), keyStorePassword);

        //Postconditions
        final PrivateKey privateKey = (PrivateKey) rootKeyStore.getKey(ROOT_ALIAS, keyStorePassword);
        assert privateKey != null;

    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException
            | SignatureException | InvalidKeyException | IOException | KeyStoreException | CertificateException
            | UnrecoverableKeyException ex) {
        throw new TexaiException(ex);
    }
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * This method generates a certificate from a base64 encoded certificate string and add to the configured trust
 * store.// ww w.  j  ava 2 s .  com
 *
 * @param base64Cert : The base 64 encoded string of the server certificate.
 * @param alias      : The alias for the certificate.
 * @return : ResponseCode which matches the execution result.
 *
 * Response Codes.
 * SUCCESS : If certificate added successfully.
 * INTERNAL_SERVER_ERROR : If any internal error occurred
 * ALIAS_EXISTS_IN_TRUST_STORE : If the alias exists in trust store.
 * CERTIFICATE_EXPIRED : If the given certificate is expired.
 */
public ResponseCode addCertificateToTrustStore(String base64Cert, String alias) {

    boolean isCertExists = false;
    boolean expired = false;
    InputStream serverCert = null;
    try {
        //Decode base64 encoded certificate.
        byte[] cert = (Base64.decodeBase64(base64Cert.getBytes(CHARSET_UTF_8)));
        serverCert = new ByteArrayInputStream(cert);
        if (serverCert.available() == 0) {
            log.error("Certificate is empty for the provided alias " + alias);
            return ResponseCode.INTERNAL_SERVER_ERROR;
        }

        //Read the client-truststore.jks into a KeyStore.
        File trustStoreFile = new File(TRUST_STORE);
        localTrustStoreStream = new FileInputStream(trustStoreFile);
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD);

        CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        while (serverCert.available() > 0) {
            Certificate certificate = cf.generateCertificate(serverCert);
            //Check whether the Alias exists in the trust store.
            if (trustStore.containsAlias(alias)) {
                isCertExists = true;
            } else {
                /*
                * If alias is not exists, check whether the certificate is expired or not. If expired set the
                * expired flag.
                * */
                X509Certificate x509Certificate = (X509Certificate) certificate;
                if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) {
                    expired = true;
                    if (log.isDebugEnabled()) {
                        log.debug("Provided certificate is expired.");
                    }
                } else {
                    //If not expired add the certificate to trust store.
                    trustStore.setCertificateEntry(alias, certificate);
                }
            }
        }
        fileOutputStream = new FileOutputStream(trustStoreFile);
        trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD);
        responseCode = expired ? ResponseCode.CERTIFICATE_EXPIRED
                : isCertExists ? ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE : ResponseCode.SUCCESS;
    } catch (CertificateException e) {
        log.error("Error loading certificate.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (FileNotFoundException e) {
        log.error("Error reading/ writing to the certificate file.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (NoSuchAlgorithmException e) {
        log.error("Could not find the algorithm to load the certificate.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (UnsupportedEncodingException e) {
        log.error("Error retrieving certificate from String", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (KeyStoreException e) {
        log.error("Error reading certificate contents.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (IOException e) {
        log.error("Error in loading the certificate.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } finally {
        closeStreams(localTrustStoreStream, fileOutputStream, serverCert);
    }
    return responseCode;
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

void importPrivateKey(String keyAlias, String keyPassword, InputStream fl, InputStream certstream)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException,
        KeyStoreException {//from  w w  w  . j av a 2 s .c  om
    KeyInfoManager keyInfoManager = null;

    writeLock.lock();
    try {
        keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
        KeyStore ks = loadKeyStore(getKeyStoreParameters(), keyInfoManager);

        // loading Key
        byte[] keyBytes = new byte[fl.available()];
        KeyFactory kf = KeyFactory.getInstance("RSA");
        fl.read(keyBytes, 0, fl.available());
        fl.close();
        PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes);
        PrivateKey key = kf.generatePrivate(keysp);

        // loading CertificateChain
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        @SuppressWarnings("rawtypes")
        Collection c = cf.generateCertificates(certstream);
        Certificate[] certs = new Certificate[c.toArray().length];

        certs = (Certificate[]) c.toArray(new Certificate[0]);

        // storing keystore
        ks.setKeyEntry(keyAlias, key, keyPassword.toCharArray(), certs);

        if (logger.isDebugEnabled()) {
            logger.debug("Key and certificate stored.");
            logger.debug("Alias:" + keyAlias);
        }

        ks.store(new FileOutputStream(getKeyStoreParameters().getLocation()), keyPassword.toCharArray());
    } finally {
        if (keyInfoManager != null) {
            keyInfoManager.clear();
        }

        writeLock.unlock();
    }
}

From source file:com.mhise.util.MHISEUtil.java

public static boolean saveImportedCertificateToDevice(String certificate, String password, Context ctx,
        String certName) {//from   ww w  .j  a v  a  2 s . c  o  m
    boolean isPasswordCorrect = false;

    byte[] certificatebytes = null;

    try {
        certificatebytes = Base64.decode(certificate, Base64.DEFAULT);
    } catch (IllegalArgumentException e) {
        // TODO: handle exception
        Logger.debug("MHISEUtil-->saveImportedCertificateToDevice", "" + e);
    }
    KeyStore localTrustStore = null;
    try {
        localTrustStore = KeyStore.getInstance("PKCS12");
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream is = new ByteArrayInputStream(certificatebytes);
    try {
        localTrustStore.load(is, password.toCharArray());
        isPasswordCorrect = true;

    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }

    OutputStream fos = null;
    try {
        //<<<<<<< .mine
        //SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,Context.MODE_PRIVATE);
        //String  storeName =sharedPreferences.getString(Constants.KEY_CERT_NAME, null);

        File _mobiusDirectory = new File(Constants.defaultP12StorePath);

        if (!_mobiusDirectory.exists()) {
            _mobiusDirectory.mkdir();
        }

        File file = new File(Constants.defaultP12StorePath + certName);
        fos = new FileOutputStream(file);
        //fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE);
        localTrustStore.store(fos, MHISEUtil.getStrongPassword(certName).toCharArray());
        /*//=======
                    //SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,Context.MODE_PRIVATE);
                    //String  storeName =sharedPreferences.getString(Constants.KEY_CERT_NAME, null);
                            
                            
                    File file = new File(Constants.defaultP12StorePath+certName);
                     fos = new FileOutputStream(file);
                    //fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE);
                    localTrustStore.store(fos,MHISEUtil.getStrongPassword(certName).toCharArray());
        >>>>>>> .r4477*/
        fos.close();

        Enumeration<String> aliases = null;
        try {
            aliases = localTrustStore.aliases();
        } catch (KeyStoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //boolean isInstalledCertificateValid = false;

        while (aliases.hasMoreElements()) {

            String alias = aliases.nextElement();
            java.security.cert.X509Certificate cert = null;
            try {
                cert = (X509Certificate) localTrustStore.getCertificate(alias);
            } catch (KeyStoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            SharedPreferences sharedPreferences1 = ctx.getSharedPreferences(Constants.PREFS_NAME,
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences1.edit();

            Log.i("Imported certificate serial number", "" + cert.getSerialNumber().toString(16));
            editor.putString(Constants.KEY_SERIAL_NUMBER, "" + cert.getSerialNumber().toString(16));
            editor.commit();

        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return isPasswordCorrect;
}

From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java

@Override
public void init(final CryptoToken cryptoToken, final CA ca,
        final AvailableCustomCertificateExtensionsConfiguration cceConfig) throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">init");
    }// w ww .  j a  v  a2s.  c  o m
    if (info.getStatus() != ExtendedCAServiceInfo.STATUS_ACTIVE) {
        if (log.isDebugEnabled()) {
            log.debug("Not generating certificates for inactive service");
        }
    } else {
        // lookup keystore passwords      
        final String keystorepass = StringTools.passwordDecryption(EjbcaConfiguration.getCaCmsKeyStorePass(),
                "ca.cmskeystorepass");
        // Currently only RSA keys are supported
        final CmsCAServiceInfo info = (CmsCAServiceInfo) getExtendedCAServiceInfo();
        // Create KeyStore       
        final KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(null, null);
        final KeyPair cmskeys = KeyTools.genKeys(info.getKeySpec(), info.getKeyAlgorithm());
        // A simple hard coded certificate profile that works for the CMS CA service
        final CertificateProfile certProfile = new CertificateProfile(
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        certProfile.setUseKeyUsage(true);
        certProfile.setKeyUsage(new boolean[9]);
        certProfile.setKeyUsage(CertificateConstants.DIGITALSIGNATURE, true);
        certProfile.setKeyUsage(CertificateConstants.KEYENCIPHERMENT, true);
        certProfile.setKeyUsage(CertificateConstants.DATAENCIPHERMENT, true);
        certProfile.setKeyUsageCritical(true);
        final EndEntityInformation eeInformation = new EndEntityInformation("NOUSERNAME", info.getSubjectDN(),
                0, info.getSubjectAltName(), "NOEMAIL", 0, new EndEntityType(), 0, 0, null, null, 0, 0, null);
        final Certificate certificate = ca.generateCertificate(cryptoToken, eeInformation, cmskeys.getPublic(),
                -1, null, ca.getEncodedValidity(), certProfile, null, cceConfig);
        certificatechain = new ArrayList<Certificate>();
        certificatechain.add(certificate);
        certificatechain.addAll(ca.getCertificateChain());
        privKey = cmskeys.getPrivate();
        keystore.setKeyEntry(PRIVATESIGNKEYALIAS, cmskeys.getPrivate(), null,
                (Certificate[]) certificatechain.toArray(new Certificate[certificatechain.size()]));
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        keystore.store(baos, keystorepass.toCharArray());
        data.put(KEYSTORE, new String(Base64.encode(baos.toByteArray())));
    }
    setStatus(info.getStatus());
    this.info = new CmsCAServiceInfo(info.getStatus(), getSubjectDN(), getSubjectAltName(),
            (String) data.get(KEYSPEC), (String) data.get(KEYALGORITHM), certificatechain);
    if (log.isTraceEnabled()) {
        log.trace("<init");
    }
}