Example usage for java.security KeyStore setCertificateEntry

List of usage examples for java.security KeyStore setCertificateEntry

Introduction

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

Prototype

public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException 

Source Link

Document

Assigns the given trusted certificate to the given alias.

Usage

From source file:com.vmware.identity.idm.server.clientcert.IdmClientCertificateValidator.java

/**
 *
 * @return keyStore representing that containing the trust CA certificates of the tenant
 * @throws InvalidArgumentException// www  .  ja va  2s  .  c  o  m
 */
private KeyStore getTrustedClientCaStore() throws InvalidArgumentException {
    KeyStore trustedClientCaStore;

    if (certPolicy == null || certPolicy.getTrustedCAs() == null) {
        throw new InvalidArgumentException("Null client certificate policy or trust ca certficagtes.");
    }
    try {
        trustedClientCaStore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e1) {
        throw new InvalidArgumentException("Failed in creating a keyStore instance: ", e1);
    }
    try {
        trustedClientCaStore.load(null, null);
    } catch (NoSuchAlgorithmException | CertificateException | IOException e1) {
        throw new InvalidArgumentException("Failed in initializing a keyStore instance: " + e1.getMessage(),
                e1);
    }
    for (Certificate trustCa : certPolicy.getTrustedCAs()) {
        X509Certificate x509Cert = (X509Certificate) trustCa;
        try {
            trustedClientCaStore.setCertificateEntry(x509Cert.getSubjectX500Principal().getName(), trustCa);
        } catch (KeyStoreException e) {
            throw new InvalidArgumentException("Failed in storing a ca cert to keyStore: " + e.getMessage(), e);
        }
    }
    return trustedClientCaStore;
}

From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java

private static final void importCertificate(final String url, final KeyStore trustStore) throws Exception {
    final URL url2 = new URL(url);
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    final X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    final SavingTrustManager trustManager = new SavingTrustManager(defaultTrustManager);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(url2.getHost(),
            url2.getPort() > 0 ? url2.getPort() : 443);
    socket.setSoTimeout(10000);/*  w  ww  .  j  a  v  a  2  s  .c o m*/
    try {
        socket.startHandshake();
        socket.close();
    } catch (SSLException e) {
    }

    final X509Certificate[] chain = trustManager.chain;
    if (chain == null) {
        LOGGER.error("Could not obtain server certificate chain from: " + url);
        return;
    }

    final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    final MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        final X509Certificate cert = chain[i];
        final String alias = url2.getHost() + "-" + (i + 1);
        if (!trustStore.containsAlias(alias)) {
            sha1.update(cert.getEncoded());
            md5.update(cert.getEncoded());
            LOGGER.trace("Importing certificate to trusted keystore >> " + "Subject: " + cert.getSubjectDN()
                    + ", Issuer: " + cert.getIssuerDN() + ", SHA1: " + printHexBinary(sha1.digest()) + ", MD5: "
                    + printHexBinary(md5.digest()) + ", Alias: " + alias);
            trustStore.setCertificateEntry(alias, cert);
        }
    }
}

From source file:jenkins.plugins.publish_over_ftp.BapFtpHostConfiguration.java

public FTPClient createFTPClient() throws GeneralSecurityException, FileNotFoundException, IOException {
    if (useFtpOverTls) {
        FTPSClient c = new FTPSClient(false);

        KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
        String trustStorePath = System.getProperty("javax.net.ssl.trustStore");
        if (trustStorePath != null) {
            String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
            if (trustStorePassword != null) {
                ts.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray());
            } else {
                ts.load(new FileInputStream(trustStorePath), null);
            }/*from   w  w w.  j  a v a 2  s .c om*/
        } else {
            ts.load(null);
        }

        if (trustedCertificate != null) {
            InputStream certStream = new ByteArrayInputStream(trustedCertificate.getBytes());
            X509Certificate x509certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
                    .generateCertificate(certStream);
            ts.setCertificateEntry(x509certificate.getSubjectDN().getName(), x509certificate);
        }

        c.setTrustManager(TrustManagerUtils.getDefaultTrustManager(ts));

        return c;
    }
    return new FTPClient();
}

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

public static KeyStore addSiteTrustChain(final String sitehostname, final int httpsport,
        final KeyStore keystore, final char[] passphrase) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    final SSLContext context = SSLContext.getInstance("TLS");
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keystore);//from  w  w  w. j  ava2s. c o  m
    final X509TrustManager dtm = (X509TrustManager) tmf.getTrustManagers()[0];
    final MyTrustManager tm = new MyTrustManager(dtm);
    context.init(null, new TrustManager[] { tm }, null);
    final SSLSocketFactory factory = context.getSocketFactory();
    final SSLSocket socket = (SSLSocket) factory.createSocket(sitehostname, httpsport);
    socket.setSoTimeout(10000);
    try {
        System.out.println("Starting SSL handshake...");
        socket.startHandshake();
        socket.close();
        System.out.println("Certificate for server " + sitehostname + " is already trusted");
    } catch (SSLException e) {
        final X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.err.println("Could not obtain server certificate chain");
            return keystore;
        }
        System.out.println("Server sent " + chain.length + " certificate(s):");
        for (int i = 0; i < chain.length; i++) {
            final X509Certificate cert = chain[i];
            MessageDigest.getInstance("SHA1").update(cert.getEncoded());
            MessageDigest.getInstance("MD5").update(cert.getEncoded());
            final String alias = sitehostname + "-" + (i + 1);
            keystore.setCertificateEntry(alias, cert);
            System.out.println("Added certificate to keystore using alias '" + alias + "'");
        }
    }
    return keystore;
}

From source file:org.ejbca.ui.web.pub.CertDistServlet.java

private void handleCaChainCommands(AuthenticationToken administrator, String issuerdn, int caid, String format,
        HttpServletResponse res) throws IOException, NoSuchFieldException {
    try {/*from   ww  w  .  j  a  va2s.c om*/
        Certificate[] chain = getCertificateChain(administrator, caid, issuerdn);
        // Reverse the chain to get proper ordering for chain file
        // (top-level CA first, requested CA last).
        ArrayUtils.reverse(chain);

        // Construct the filename based on requested CA. Fail-back to
        // name "ca-chain.EXT".
        String filename = RequestHelper.getFileNameFromCertNoEnding(chain[chain.length - 1], "ca") + "-chain."
                + format.toLowerCase();

        byte[] outbytes = new byte[0];
        // Encode and send back
        if ((format == null) || StringUtils.equalsIgnoreCase(format, "pem")) {
            outbytes = CertTools.getPemFromCertificateChain(Arrays.asList(chain));
        } else {
            // Create a JKS truststore with the CA certificates in
            final KeyStore store = KeyStore.getInstance("JKS");
            store.load(null, null);
            for (int i = 0; i < chain.length; i++) {
                String cadn = CertTools.getSubjectDN(chain[i]);
                String alias = CertTools.getPartFromDN(cadn, "CN");
                if (alias == null) {
                    alias = CertTools.getPartFromDN(cadn, "O");
                }
                if (alias == null) {
                    alias = "cacert" + i;
                }
                alias = StringUtils.replaceChars(alias, ' ', '_');
                alias = StringUtils.substring(alias, 0, 15);
                store.setCertificateEntry(alias, chain[i]);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                store.store(out, "changeit".toCharArray());
                out.close();
                outbytes = out.toByteArray();
            }
        }
        // We must remove cache headers for IE
        ServletUtils.removeCacheHeaders(res);
        res.setHeader("Content-disposition",
                "attachment; filename=\"" + StringTools.stripFilename(filename) + "\"");
        res.setContentType("application/octet-stream");
        res.setContentLength(outbytes.length);
        res.getOutputStream().write(outbytes);
        log.debug("Sent CA certificate chain to client, len=" + outbytes.length + ".");
    } catch (CertificateEncodingException e) {
        log.debug("Error getting CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting CA certificate chain.");
    } catch (KeyStoreException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (NoSuchAlgorithmException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (CertificateException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (EJBException e) {
        log.debug("CA does not exist: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND,
                "CA does not exist: " + HTMLTools.htmlescape(e.getMessage()));
    } catch (AuthorizationDeniedException e) {
        log.debug("Authotization denied: ", e);
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Authorization denied: " + HTMLTools.htmlescape(e.getMessage()));
    }
}

From source file:org.signserver.module.xades.signer.XAdESSignerUnitTest.java

/**
 * Internal method to perform a signing operation.
 *
 * @param token Crypto token to use/* w  w  w .  ja v  a2  s .c om*/
 * @param config Signer configuration to use for the test
 * @param toSign The XML document to sign
 * @param useCertCredential Generate credential for the request from the mocked signer certificate
 * @param username Username to generate a username/password credential in the request context, if null, no credential is passed
 * @return Verification result
 * @throws Exception
 */
private XAdESVerificationResult getVerificationResult(final MockedCryptoToken token, final WorkerConfig config,
        String toSign, final boolean useCertCredential, final String username) throws Exception {
    XAdESSigner instance = new MockedXAdESSigner(token);

    instance.init(4711, config, null, null);

    final RequestContext requestContext = new RequestContext();

    requestContext.put(RequestContext.TRANSACTION_ID, "0000-100-1");

    if (useCertCredential) {
        final CertificateClientCredential cred = new CertificateClientCredential("CN=foo", "123456789abc");

        requestContext.put(RequestContext.CLIENT_CREDENTIAL, cred);
    } else if (username != null) {
        final UsernamePasswordClientCredential cred = new UsernamePasswordClientCredential(username, "foobar");

        requestContext.put(RequestContext.CLIENT_CREDENTIAL, cred);
    }

    GenericSignRequest request = new GenericSignRequest(100, toSign.getBytes("UTF-8"));
    GenericSignResponse response = (GenericSignResponse) instance.processData(request, requestContext);

    byte[] data = response.getProcessedData();
    final String signedXml = new String(data);
    LOG.debug("signedXml: " + signedXml);

    // Validation: setup
    CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters());
    KeyStore trustAnchors = KeyStore.getInstance("JKS");
    trustAnchors.load(null, "foo123".toCharArray());
    List<Certificate> chain = token.getCertificateChain(ICryptoToken.PURPOSE_SIGN);
    System.out.println("trust anchor: " + chain.get(chain.size() - 1));
    trustAnchors.setCertificateEntry("rootcert", chain.get(chain.size() - 1)); // Simply assume last cert in chain is the trust anchor

    CertificateValidationProvider certValidator = new PKIXCertificateValidationProvider(trustAnchors, false,
            certStore);

    XadesVerificationProfile p = new XadesVerificationProfile(certValidator);
    XadesVerifier verifier = p.newVerifier();

    // Validation: parse
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.parse(new ByteArrayInputStream(data));
    Element node = doc.getDocumentElement();

    XAdESVerificationResult r = verifier.verify(node, new SignatureSpecificVerificationOptions());

    return r;
}

From source file:org.lockss.util.KeyStoreUtil.java

public static void createSharedPLNKeyStores(File dir, List hostlist, File pubKeyStoreFile,
        String pubKeyStorePassword, SecureRandom rng) throws Exception {

    String[] hosts = (String[]) hostlist.toArray(new String[0]);
    KeyStore[] ks = new KeyStore[hosts.length];
    String[] pwd = new String[hosts.length];

    for (int i = 0; i < hosts.length; i++) {
        ks[i] = null;//from   ww  w .  j  ava 2  s  . c  o m
        pwd[i] = null;
    }
    /*
     * Create or read the public keystore
     */
    KeyStore pubStore = createKeystore0();
    if (pubKeyStoreFile.exists()) {
        FileInputStream fis = new FileInputStream(pubKeyStoreFile);
        try {
            log.debug("Trying to read PubStore from " + pubKeyStoreFile);
            pubStore.load(fis, pubKeyStorePassword.toCharArray());
        } catch (Exception e) {
            log.debug("ks.load(" + pubKeyStoreFile + ")", e);
            throw e;
        } finally {
            IOUtil.safeClose(fis);
        }
    } else {
        pubStore.load(null, pubKeyStorePassword.toCharArray());
    }
    /*
     * Create a password for each machine's keystore
     */
    for (int i = 0; i < hosts.length; i++) {
        if (pwd[i] == null) {
            pwd[i] = randomString(20, rng);
        }
    }
    /*
     * Create a keystore for each machine with a certificate
     * and a private key.
     */
    for (int i = 0; i < hosts.length; i++) {
        String host = hosts[i];
        String certAlias = host + crtSuffix;
        Properties p = new Properties();
        p.put(PROP_KEY_ALIAS, host + keySuffix);
        p.put(PROP_CERT_ALIAS, certAlias);
        p.put(PROP_KEY_PASSWORD, pwd[i]);
        p.put(PROP_KEYSTORE_PASSWORD, host);
        ks[i] = createKeyStore(p);

        /*
         * Add its certificate to the public keystore.
         */
        java.security.cert.Certificate cert = ks[i].getCertificate(certAlias);
        log.debug("About to store " + certAlias + " in keyStore for " + hosts[i]);
        try {
            pubStore.setCertificateEntry(certAlias, cert);
        } catch (KeyStoreException e) {
            log.debug("pubStore.setCertificateEntry(" + certAlias + "," + host + ") threw " + e);
            throw e;
        }
    }
    /*
     * Write out each keyStore and its password
     */
    for (int i = 0; i < hosts.length; i++) {
        storeKeyStore(ks[i], new File(dir, hosts[i] + ".jceks"), hosts[i]);
        writePasswordFile(new File(dir, hosts[i] + ".pass"), pwd[i]);
    }
    storeKeyStore(pubStore, pubKeyStoreFile, pubKeyStorePassword);

    if (log.isDebug()) {
        for (int i = 0; i < hosts.length; i++) {
            listKeyStore(hosts, ks, pwd, i);
        }
    }
}

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java

/**
 * Generate a socket factory using supplied key and trust stores 
 *///from  w ww.  j a v a 2s .c o  m
protected SSLConnectionSocketFactory getSocketFactory() throws IOException {
    TrustManager[] trustManagers = null;
    KeyManager[] keyManagers = null;

    try {
        /* trust managers */
        if (caCertificateFile != null) {
            KeyStore trustStore;
            int cn = 0;

            log.info("Setting x509 trust from " + caCertificateFile);

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            FileInputStream in = new FileInputStream(caCertificateFile);
            Collection certs = cf.generateCertificates(in);

            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            Iterator cit = certs.iterator();
            while (cit.hasNext()) {
                X509Certificate cert = (X509Certificate) cit.next();
                log.info(" adding " + cert.getSubjectX500Principal().toString());
                System.out.println(" adding " + cert.getSubjectX500Principal().toString());
                trustStore.setCertificateEntry("CACERT" + cn, cert);
                cn += 1;
            }
            tmf.init(trustStore);
            trustManagers = tmf.getTrustManagers();
        } else { // no verification
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    return;
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    return;
                }
            } };
        }

        /* key manager */
        if (certificateFile != null && keyFile != null) {
            KeyStore keyStore;
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            FileInputStream in = new FileInputStream(certificateFile);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
            PKCS1 pkcs = new PKCS1();
            log.info("reading key file: " + keyFile);
            PrivateKey key = pkcs.readKey(keyFile);

            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain);
            kmf.init(keyStore, "pw".toCharArray());
            keyManagers = kmf.getKeyManagers();
        }

        /* socket factory */

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagers, null);
        return new SSLConnectionSocketFactory(ctx);

    } catch (IOException e) {
        log.error("error reading cert or key error: " + e);
    } catch (KeyStoreException e) {
        log.error("keystore error: " + e);
    } catch (NoSuchAlgorithmException e) {
        log.error("sf error: " + e);
    } catch (KeyManagementException e) {
        log.error("sf error: " + e);
    } catch (CertificateException e) {
        log.error("sf error: " + e);
    } catch (UnrecoverableKeyException e) {
        log.error("sf error: " + e);
    }

    return null;

}

From source file:edu.vt.middleware.crypt.KeyStoreCli.java

/**
 * Imports a certificate or key pair into the keystore.
 *
 * @param  line  Parsed command line arguments container.
 *
 * @throws  Exception  On errors.//from ww  w  .j  a v  a2 s.c om
 */
protected void doImport(final CommandLine line) throws Exception {
    validateOptions(line);

    final KeyStore store = readKeyStore(line);
    final String alias = line.getOptionValue(OPT_ALIAS);
    final File certFile = new File(line.getOptionValue(OPT_CERT));
    if (line.hasOption(OPT_KEY)) {
        final File keyFile = new File(line.getOptionValue(OPT_KEY));
        final char[] passChars = line.getOptionValue(OPT_PASS).toCharArray();
        final PrivateKey key = CryptReader.readPrivateKey(keyFile);
        final Certificate[] chain = CryptReader.readCertificateChain(certFile);
        System.err.println("Read certificate chain of length " + chain.length + ":");
        for (int i = 0; i < chain.length; i++) {
            System.out.println("===== Certificate [" + i + "] =====");
            printCertificate(chain[i]);
        }
        store.setKeyEntry(alias, key, passChars, chain);
        System.err.println("Imported key entry " + alias);
    } else {
        final Certificate cert = CryptReader.readCertificate(certFile);
        System.err.println("Read certificate:");
        printCertificate(cert);
        store.setCertificateEntry(alias, cert);
        System.err.println("Imported trusted cert entry " + alias);
    }

    final OutputStream os = new FileOutputStream(new File(line.getOptionValue(OPT_STORE)));
    try {
        store.store(os, line.getOptionValue(OPT_PASS).toCharArray());
    } finally {
        os.close();
    }
}

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

private void saveNodeCertificateChain(KeyStore keyStore, Key key, String keyPassword, X509Certificate nodeCert,
        X509Certificate[] chain) {
    if (keyPassword == null) {
        keyPassword = "";
    }// w  w  w . j  av  a2 s.c o m
    X509Certificate caCert = getCACertificate(keyStore);

    if (chain.length < 1) {
        throw new CertificateException("No certificates avaialble");
    }

    if (chain.length > 1) {
        // we have to trust the parents... the end of the chain must be our CA
        try {
            final int caIdx = chain.length - 1;
            if (caCert == null) {
                // if we don't have a CA cert yet, install that now
                log.info("Installing trusted CA certificate {}", chain[caIdx].getSubjectDN());
                keyStore.setCertificateEntry(caAlias, chain[caIdx]);
                caCert = chain[caIdx];
            } else {
                // verify CA is the same... maybe we shouldn't do this?
                if (!chain[caIdx].getSubjectDN().equals(caCert.getSubjectDN())) {
                    throw new CertificateException("Chain CA " + chain[caIdx].getSubjectDN().getName()
                            + " does not match expected " + caCert.getSubjectDN().getName());
                }
                if (!chain[caIdx].getIssuerDN().equals(caCert.getIssuerDN())) {
                    throw new CertificateException("Chain CA " + chain[caIdx].getIssuerDN().getName()
                            + " does not match expected " + caCert.getIssuerDN().getName());
                }
            }
            // install intermediate certs...
            for (int i = caIdx - 1, j = 1; i > 0; i--, j++) {
                String alias = caAlias + "sub" + j;
                log.info("Installing trusted intermediate certificate {}", chain[i].getSubjectDN());
                keyStore.setCertificateEntry(alias, chain[i]);
            }
        } catch (KeyStoreException e) {
            throw new CertificateException("Error storing CA chain", e);
        }
    } else {
        // put CA at end of chain
        if (caCert == null) {
            throw new CertificateException("No CA certificate available");
        }
        chain = new X509Certificate[] { chain[0], caCert };
    }

    // the issuer must be our CA cert subject...
    if (!chain[0].getIssuerDN().equals(chain[1].getSubjectDN())) {
        throw new CertificateException("Issuer " + chain[0].getIssuerDN().getName()
                + " does not match expected " + chain[1].getSubjectDN().getName());
    }

    // the subject must be our node's existing subject...
    if (!chain[0].getSubjectDN().equals(nodeCert.getSubjectDN())) {
        throw new CertificateException("Subject " + chain[0].getIssuerDN().getName()
                + " does not match expected " + nodeCert.getSubjectDN().getName());
    }

    log.info("Installing node certificate {} reply {} issued by {}", chain[0].getSerialNumber(),
            chain[0].getSubjectDN().getName(), chain[0].getIssuerDN().getName());
    try {
        keyStore.setKeyEntry(nodeAlias, key, keyPassword.toCharArray(), chain);
    } catch (KeyStoreException e) {
        throw new CertificateException("Error opening node certificate", e);
    }
}