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:org.panbox.core.pairing.file.PanboxFilePairingUtils.java

/**
 * Stores a pairing file at the specified path for the specified device and
 * type// ww  w  . j  a  va  2  s . co  m
 * 
 * @param outputFile
 *            Pairing file to be saved
 * @param devicename
 *            Name of the device that should be paired
 * @param password
 *            Password of the identity
 */
public static PanboxFilePairingWriteReturnContainer storePairingFile(File outputFile, String devicename,
        char[] password, PairingType type, DeviceType devType, String eMail, String firstName, String lastName,
        PrivateKey privEncKey, X509Certificate encCert, PrivateKey privSignKey, X509Certificate signCert,
        Map<String, X509Certificate> devices, Collection<VCard> contacts)
        throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
    logger.debug("PanboxFilePairingUtils : storePairingFile : Storing pairing container to: "
            + outputFile.getAbsolutePath());

    ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(outputFile));

    // 1. add device name to pairing file
    ZipArchiveEntry entry = new ZipArchiveEntry("devicename");
    entry.setSize(devicename.getBytes().length);
    out.putArchiveEntry(entry);

    out.write(devicename.getBytes());
    out.flush();

    out.closeArchiveEntry();

    // 2. add device name to pairing file
    entry = new ZipArchiveEntry("email");
    entry.setSize(eMail.getBytes().length);
    out.putArchiveEntry(entry);

    out.write(eMail.getBytes());
    out.flush();

    out.closeArchiveEntry();

    // 3. add device name to pairing file
    entry = new ZipArchiveEntry("firstname");
    entry.setSize(firstName.getBytes().length);
    out.putArchiveEntry(entry);

    out.write(firstName.getBytes());
    out.flush();

    out.closeArchiveEntry();

    // 4. add device name to pairing file
    entry = new ZipArchiveEntry("lastname");
    entry.setSize(lastName.getBytes().length);
    out.putArchiveEntry(entry);

    out.write(lastName.getBytes());
    out.flush();

    out.closeArchiveEntry();

    // 5. generate and add a new device key + cert for the newly device
    KeyPair devKey = CryptCore.generateKeypair();
    X509Certificate devCert = CryptCore.createSelfSignedX509Certificate(devKey.getPrivate(), devKey.getPublic(),
            new PairingIPersonDummy(eMail, firstName, lastName));

    KeyStore devKeyStore = KeyStore.getInstance("PKCS12");
    devKeyStore.load(null, null);
    devKeyStore.setKeyEntry(devicename, (Key) devKey.getPrivate(), password, new Certificate[] { devCert });
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    devKeyStore.store(baos, password);
    baos.flush();

    byte[] data = baos.toByteArray();
    entry = new ZipArchiveEntry("devicekey.p12");
    entry.setSize(data.length);
    out.putArchiveEntry(entry);
    out.write(data);
    out.flush();

    out.closeArchiveEntry();

    // 6. add device certs and names for all known devices

    baos = new ByteArrayOutputStream();
    ByteArrayOutputStream deviceNamesFile = new ByteArrayOutputStream();
    KeyStore deviceKeyStore = KeyStore.getInstance("BKS");
    deviceKeyStore.load(null, null);
    int i = 0;

    for (Entry<String, X509Certificate> device : devices.entrySet()) {
        deviceKeyStore.setCertificateEntry("device" + i, device.getValue());
        deviceNamesFile.write(("device" + i + DELIMITER + device.getKey() + "\n").getBytes());
        ++i;
    }

    deviceKeyStore.store(baos, password);
    baos.flush();
    deviceNamesFile.flush();

    byte[] data2 = deviceNamesFile.toByteArray();
    entry = new ZipArchiveEntry("knownDevices.list");
    entry.setSize(data2.length);
    out.putArchiveEntry(entry);
    out.write(data2);
    out.flush();

    data = baos.toByteArray();
    entry = new ZipArchiveEntry("knownDevices.bks");
    entry.setSize(data.length);
    out.putArchiveEntry(entry);
    out.write(data);
    out.flush();

    // 7. add vcard for all known contacts

    File tempContacts = File.createTempFile("panboxContacts", null);
    AbstractAddressbookManager.exportContacts(contacts, tempContacts);
    FileInputStream fis = new FileInputStream(tempContacts);
    data = new byte[(int) tempContacts.length()];
    fis.read(data);
    fis.close();
    tempContacts.delete();

    entry = new ZipArchiveEntry("contacts.vcard");
    entry.setSize(data.length);
    out.putArchiveEntry(entry);
    out.write(data);
    out.flush();

    // 8. add owner certs or keys in case of main/restricted
    KeyStore ownerKeyStore = null;
    if (type == PairingType.MASTER) {
        ownerKeyStore = KeyStore.getInstance("PKCS12");
        ownerKeyStore.load(null, null);
        ownerKeyStore.setKeyEntry("ownerEncKey", privEncKey, password, new Certificate[] { encCert });
        ownerKeyStore.setKeyEntry("ownerSignKey", privSignKey, password, new Certificate[] { signCert });
        entry = new ZipArchiveEntry("ownerKeys.p12");
    } else {
        ownerKeyStore = KeyStore.getInstance("BKS");
        ownerKeyStore.load(null, null);
        ownerKeyStore.setCertificateEntry("ownerEncCert", encCert);
        ownerKeyStore.setCertificateEntry("ownerSignCert", signCert);
        entry = new ZipArchiveEntry("ownerCerts.bks");
    }
    baos = new ByteArrayOutputStream();
    ownerKeyStore.store(baos, password);
    baos.flush();

    data = baos.toByteArray();
    entry.setSize(data.length);
    out.putArchiveEntry(entry);
    out.write(data);
    out.flush();

    out.closeArchiveEntry();

    out.flush();
    out.close();
    logger.debug("PanboxFilePairingUtils : storePairingFile : Storing pairing container finished.");

    return new PanboxFilePairingWriteReturnContainer(devicename, devCert, devType);
}

From source file:com.guster.skywebservice.library.webservice.SkyHttp.java

public static void setSSLCertificate(InputStream certificateFile) throws CertificateException, IOException,
        KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate cert = cf.generateCertificate(certificateFile);

    certificateFile.close();/*w ww.j  a  v a 2 s  . com*/

    // create a keystore containing the certificate
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", cert);

    // create a trust manager for our certificate
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);

    // create a SSLContext that uses our trust manager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);

    // set socket factory
    setSSLSocketFactory(context.getSocketFactory());
}

From source file:com.vmware.identity.openidconnect.client.TestUtils.java

static void populateSSLCertificates(String domainControllerFQDN, int domainControllerPort, KeyStore keyStore)
        throws Exception {
    AfdClient afdClient = new AfdClient(domainControllerFQDN, domainControllerPort,
            NoopHostnameVerifier.INSTANCE, new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override/*www .ja  v a 2  s.c om*/
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build());

    List<CertificateDTO> certs = afdClient.vecs().getSSLCertificates();
    int index = 1;
    for (CertificateDTO cert : certs) {
        keyStore.setCertificateEntry(String.format("VecsSSLCert%d", index), cert.getX509Certificate());
        index++;
    }
}

From source file:com.arm.connector.bridge.core.Utils.java

public static String createKeystore(ErrorLogger logger, String base, String sep, String filename,
        X509Certificate cert, PrivateKey priv_key, String pw) {
    String basedir = base + File.separator + sep;
    String keystore_filename = basedir + File.separator + filename;

    try {// w ww .  j  a v a 2 s .com
        // first create the directory if it does not exist
        File file = new File(basedir);

        // make the directories
        logger.info("createKeystore: Making directories for keystore...");
        file.mkdirs();

        // create the KeyStore
        logger.info("createKeystore: Creating keystore: " + keystore_filename);
        file = new File(keystore_filename);
        if (file.createNewFile()) {
            logger.info("createKeystore: keystore created:  " + keystore_filename);
        } else {
            logger.warning("createKeystore: keystore already exists " + keystore_filename);
        }

        // store data into the keystore
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(null, pw.toCharArray());

        // set the certificate, priv and pub keys
        if (cert != null) {
            Certificate[] cert_list = new Certificate[2];
            cert_list[0] = cert;
            cert_list[1] = Utils.createCACertificate(logger);

            ks.setCertificateEntry("aws", cert_list[0]);
            ks.setCertificateEntry("verisign", cert_list[1]);

            if (priv_key != null) {
                try {
                    ks.setKeyEntry("privkey", priv_key, pw.toCharArray(), cert_list);
                } catch (Exception ex2) {
                    logger.warning("createKeystore: Exception during priv addition... not added to keystore",
                            ex2);
                }
            } else {
                logger.warning("createKeystore: privkey is NULL... not added to keystore");
            }
        } else {
            logger.warning("createKeystore: certificate is NULL... not added to keystore");
        }

        try (FileOutputStream fos = new FileOutputStream(keystore_filename)) {
            // store away the keystore content
            ks.store(fos, pw.toCharArray());

            // close
            fos.flush();
        }
    } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException ex) {
        logger.warning("createKeystore: Unable to create keystore: " + keystore_filename, ex);
    }

    // return the keystore filename
    return keystore_filename;
}

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

public static void addCertificates(String[] domainNames, KeyStore keyStore,
        java.security.cert.Certificate[] certs, int i) throws KeyStoreException {
    KeyStoreException err = null;
    for (int j = 0; j < domainNames.length; j++) {
        if (j != i) {
            String alias = domainNames[j] + crtSuffix;
            log.debug("About to store " + alias + " in keyStore for " + domainNames[i]);
            try {
                keyStore.setCertificateEntry(alias, certs[j]);
            } catch (KeyStoreException e) {
                log.debug("keyStore.setCertificateEntry(" + alias + "," + domainNames[i] + ") threw " + e);
                err = e;/*  w w  w.j a va2s.  c  o  m*/
            }
        }
    }
    if (err != null) {
        throw err;
    }
}

From source file:com.streamsets.datacollector.credential.cyberark.TestWebServicesFetcher.java

private static <T extends Certificate> void createTrustStore(File file, String password, Map<String, T> certs)
        throws GeneralSecurityException, IOException {
    KeyStore ks = createEmptyKeyStore();
    for (Map.Entry<String, T> cert : certs.entrySet()) {
        ks.setCertificateEntry(cert.getKey(), cert.getValue());
    }//  w  w  w  . j av a  2s.  c om
    saveKeyStore(ks, file, password);
}

From source file:com.solace.samples.cloudfoundry.securesession.controller.SolaceController.java

/**
 * This utility function installs a certificate into the JRE's trusted
 * store. Normally you would not do this, but this is provided to
 * demonstrate how to use TLS, and have the client validate a self-signed
 * server certificate.//  w w w . j a va  2s.  com
 *
 * @throws Exception
 */
private static void importCertificate() throws Exception {

    File file = new File(CERTIFICATE_FILE_NAME);
    logger.info("Loading certificate from " + file.getAbsolutePath());

    // This loads the KeyStore from the default location
    // (i.e. default for a Clound Foundry app) using the default password.
    FileInputStream is = new FileInputStream(TRUST_STORE);
    char[] password = TRUST_STORE_PASSWORD.toCharArray();
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, password);
    is.close();

    // Create an ByteArrayInputStream stream from the
    FileInputStream fis = new FileInputStream(CERTIFICATE_FILE_NAME);
    DataInputStream dis = new DataInputStream(fis);
    byte[] bytes = new byte[dis.available()];
    dis.readFully(bytes);
    dis.close();
    ByteArrayInputStream certstream = new ByteArrayInputStream(bytes);

    // This takes that Byte Array and creates a certificate out of it.
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate certs = cf.generateCertificate(certstream);

    // Finally, store the new certificate in the keystore.
    keystore.setCertificateEntry(CERTIFICATE_ALIAS, certs);

    // Save the new keystore contents
    FileOutputStream out = new FileOutputStream(TRUST_STORE);
    keystore.store(out, password);
    out.close();

}

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

public static KeyStore readCerts(final String pemContent, final String aliasPrefix)
        throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);//from w  w  w. j  a va2 s .c o m

    final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

    final List<String> lines = readLines(pemContent);

    final StringBuilder current = new StringBuilder();
    final List<String> entries = new ArrayList<String>();
    for (final String line : lines) {
        if (line == null) {
            continue;
        }

        if (line.startsWith("-----BEGIN")) {
            current.setLength(0);
        } else if (line.startsWith("-----END")) {
            entries.add(current.toString());
        } else {
            current.append(line.trim());
        }
    }

    int i = 0;
    for (final String entry : entries) {
        final byte[] data = decodeBase64(entry);

        final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data));

        ks.setCertificateEntry(aliasPrefix + i, c);
        i++;
    }

    return ks;
}

From source file:com.ibm.iotf.client.AbstractClient.java

static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile,
        final String password) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate caCert = null;

    if (caCrtFile != null) {
        // load CA certificate
        PEMReader reader = new PEMReader(
                new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
        caCert = (X509Certificate) reader.readObject();
        reader.close();//from  ww  w.j av  a 2s.  c  om
    } else {
        ClassLoader classLoader = AbstractClient.class.getClassLoader();
        PEMReader reader = new PEMReader(
                new InputStreamReader(classLoader.getResource(SERVER_MESSAGING_PEM).openStream()));
        caCert = (X509Certificate) reader.readObject();
        reader.close();
    }

    PEMReader reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
    X509Certificate cert = (X509Certificate) reader.readObject();
    reader.close();

    // load client private key
    reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))));
    KeyPair key = (KeyPair) reader.readObject();
    reader.close();

    TrustManagerFactory tmf = null;
    if (caCert != null) {
        // CA certificate is used to authenticate server
        KeyStore caKs = KeyStore.getInstance("JKS");
        //caKs.load(null, null);
        caKs.load(null, null);
        caKs.setCertificateEntry("ca-certificate", caCert);
        tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(caKs);
    }
    // client key and certificates are sent to server so it can authenticate us
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setCertificateEntry("certificate", cert);
    ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(),
            new java.security.cert.Certificate[] { cert });
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
    kmf.init(ks, password.toCharArray());

    // finally, create SSL socket factory
    SSLContext context = SSLContext.getInstance("TLSv1.2");
    if (tmf != null) {
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        context.init(kmf.getKeyManagers(), null, null);
    }

    return context.getSocketFactory();
}

From source file:be.fgov.kszbcss.rhq.websphere.connector.security.TrustStoreManager.java

public void addCertificate(final String alias, final X509Certificate cert) throws Exception {
    execute(new TrustStoreAction() {
        public void execute(KeyStore truststore) throws Exception {
            truststore.setCertificateEntry(alias, cert);
        }//ww w .  j  a v a  2 s.  com
    }, false);
}