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.github.mrstampy.gameboot.otp.OtpTestConfiguration.java

/**
 * Client context.//  w w w. j  ava2  s . c  om
 *
 * @return the SSL context
 * @throws Exception
 *           the exception
 */
@Bean(name = CLIENT_SSL_CONTEXT)
public SSLContext clientContext() throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance(X_509);
    Certificate cert = cf.generateCertificate(getResource(CERT_LOCATION));

    KeyStore keystore = getKeyStore();
    keystore.load(null);
    keystore.setCertificateEntry(ALIAS, cert);

    return createContext(keystore, null);
}

From source file:org.candlepin.client.CustomSSLProtocolSocketFactory.java

private SSLContext createCustomSSLContext() {
    try {/*from   ww w  . j  ava2s  . co m*/
        KeyManager[] keyManagers = null;
        // Generate key managers off of the identity certificates if
        // doing client auth.
        if (clientAuth) {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            String[] keyCert = FileUtil.readKeyAndCert(configuration.getConsumerIdentityFilePath());
            kmf.init(PemUtil.pemToKeyStore(keyCert[1], keyCert[0], "password"), "password".toCharArray());
            keyManagers = kmf.getKeyManagers();
        }
        /* and provide them for the SSLContext */
        SSLContext ctx = SSLContext.getInstance("TLS");
        if (configuration.isIgnoreTrustManagers()) {
            ctx.init(keyManagers, Utils.DUMMY_TRUST_MGRS, new SecureRandom());
        } else {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            KeyStore ks2 = KeyStore.getInstance(KeyStore.getDefaultType());
            ks2.load(null, null);

            ks2.setCertificateEntry("candlepin", PemUtil.readCert("/etc/candlepin/certs/candlepin-ca.crt"));
            // ks2.load(
            // new FileInputStream(configuration.getKeyStoreFileLocation()),
            // passwd);
            tmf.init(ks2);
            ctx.init(keyManagers, tmf.getTrustManagers(), new SecureRandom());
        }

        return ctx;
    } catch (Exception e) {
        e.printStackTrace();
        throw new HttpClientError(e.getMessage());
    }
}

From source file:org.jboss.as.test.integration.logging.handlers.SocketHandlerTestCase.java

private static void createKeyStoreTrustStore(final KeyStore keyStore, final KeyStore trustStore)
        throws KeyStoreException {
    final X500Principal principal = new X500Principal(SERVER_DNS_STRING);

    final SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey
            .builder().setKeyAlgorithmName("RSA").setSignatureAlgorithmName("SHA1withRSA").setDn(principal)
            .setKeySize(1024).build();/* w  w w  .  ja va  2 s.  co  m*/
    final X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();

    keyStore.setKeyEntry(ALIAS, selfSignedX509CertificateAndSigningKey.getSigningKey(),
            KEYSTORE_CREATION_PASSWORD, new X509Certificate[] { certificate });
    trustStore.setCertificateEntry(ALIAS, certificate);
}

From source file:org.thingsboard.rule.engine.mqtt.credentials.CertPemClientCredentials.java

private TrustManagerFactory createAndInitTrustManagerFactory() throws Exception {
    X509Certificate caCertHolder;
    caCertHolder = readCertFile(caCert);

    KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    caKeyStore.load(null, null);//from  www .  j av a 2s.c  o m
    caKeyStore.setCertificateEntry("caCert-cert", caCertHolder);

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(caKeyStore);
    return trustManagerFactory;
}

From source file:edu.internet2.middleware.subject.provider.LdapPEMSocketFactory.java

protected void initManagers() {

    // trust managers
    try {/*from   w  w  w  .j av a 2 s  .  com*/
        X509Certificate cert = null;
        if (caFilename != null)
            cert = readCertificate(caFilename);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setCertificateEntry("CACERT", cert);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        trustManagers = tmf.getTrustManagers();
    } catch (Exception e) {
        log.error("ldap source cacert error: " + e);
    }

    // key managers
    if (certFilename != null && keyFilename != null) {
        char[] pw = new char[] { 0 };

        try {
            X509Certificate cert = readCertificate(certFilename);
            PKCS1 pkcs = new PKCS1();
            PrivateKey key = pkcs.readKey(keyFilename);
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null, null);
            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            ks.setKeyEntry("CERT", (Key) key, pw, chain);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, pw);
            keyManagers = kmf.getKeyManagers();
        } catch (Exception e) {
            log.error("ldap source cert/key error: " + e);
        }
    }

}

From source file:org.metaeffekt.dcc.agent.AuthenticationKeyGenerator.java

private void createTrustStore(File file, String certificateAlias, X509Certificate certificate, char[] password)
        throws GeneralSecurityException, IOException {
    final KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
    keyStore.load(null, password);/*from  ww w . j av a  2  s . c om*/

    keyStore.setCertificateEntry(certificateAlias, certificate);

    persistKeyStore(keyStore, file, password);
}

From source file:com.spotify.docker.client.DockerCertificates.java

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    try {//w ww.ja va 2  s  .  c  o m
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw new DockerCertificateException(e);
    }
}

From source file:eu.europa.esig.dss.x509.KeyStoreCertificateSource.java

public void addCertificateToKeyStore(CertificateToken certificateToken) {
    try {//  w  w w. ja v a2 s  .c  o  m
        KeyStore keyStore = getKeyStore();
        keyStore.setCertificateEntry(certificateToken.getDSSIdAsString(), certificateToken.getCertificate());
        persistKeyStore(keyStore);
    } catch (Exception e) {
        logger.error("Unable to add certificate to the keystore : " + e.getMessage(), e);
    }
}

From source file:com.spotify.sshagenttls.CertHttpsHandler.java

public void handle(final HttpsURLConnection conn) {
    final CertKey certKey;
    try {//w w w .  j  av a2  s .  com
        certKey = createCertKey();
    } catch (IOException | GeneralSecurityException e) {
        if (failOnCertError) {
            throw new RuntimeException(e);
        } else {
            LOG.warn("Error when setting up client certificates fromPaths {}. Error was '{}'. "
                    + "No cert will be sent with request.", getCertSource(), e.toString());
            LOG.debug("full exception fromPaths setting up ClientCertificate follows", e);
            return;
        }
    }

    final Certificate cert = certKey.cert();
    final PrivateKey key = certKey.key();

    // Generate a keystore password.
    // Do all this locally to not make copies of the password in memory.
    final SecureRandom random = new SecureRandom();
    final int numBytes = 60;
    final char[] keyStorePassword = new char[numBytes];
    for (int i = 0; i < numBytes; i++) {
        // Only use ASCII characters for the password. The corresponding integer range is [32, 126].
        keyStorePassword[i] = (char) (random.nextInt(95) + 32);
    }

    try {
        // We're creating a keystore in memory and putting the cert & key into it.
        // The keystore needs a password when we put the key into it, even though it's only going to
        // exist for the lifetime of the process. So we just have some random password that we use.

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("client", cert);
        keyStore.setKeyEntry("key", key, keyStorePassword, new Certificate[] { cert });

        // build an SSLContext based on our keystore, and then get an SSLSocketFactory fromPaths that
        final SSLContext sslContext = SSLContexts.custom().useProtocol("TLS")
                .loadKeyMaterial(keyStore, keyStorePassword).build();

        // Clear out arrays that had password
        Arrays.fill(keyStorePassword, '\0');

        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    } catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException
            | UnrecoverableKeyException | KeyManagementException e) {
        // so many dumb ways to die. see https://www.youtube.com/watch?v=IJNR2EpS0jw for more.
        throw new RuntimeException(e);
    }
}

From source file:org.thingsboard.rule.engine.mqtt.credentials.CertPemClientCredentials.java

private KeyManagerFactory createAndInitKeyManagerFactory() throws Exception {
    X509Certificate certHolder = readCertFile(cert);
    Object keyObject = readPrivateKeyFile(privateKey);
    char[] passwordCharArray = "".toCharArray();
    if (!StringUtils.isEmpty(password)) {
        passwordCharArray = password.toCharArray();
    }//from  w ww  . java  2s .  c  o  m

    JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC");

    PrivateKey privateKey;
    if (keyObject instanceof PEMEncryptedKeyPair) {
        PEMDecryptorProvider provider = new JcePEMDecryptorProviderBuilder().build(passwordCharArray);
        KeyPair key = keyConverter.getKeyPair(((PEMEncryptedKeyPair) keyObject).decryptKeyPair(provider));
        privateKey = key.getPrivate();
    } else if (keyObject instanceof PEMKeyPair) {
        KeyPair key = keyConverter.getKeyPair((PEMKeyPair) keyObject);
        privateKey = key.getPrivate();
    } else if (keyObject instanceof PrivateKey) {
        privateKey = (PrivateKey) keyObject;
    } else {
        throw new RuntimeException("Unable to get private key from object: " + keyObject.getClass());
    }

    KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    clientKeyStore.load(null, null);
    clientKeyStore.setCertificateEntry("cert", certHolder);
    clientKeyStore.setKeyEntry("private-key", privateKey, passwordCharArray, new Certificate[] { certHolder });

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(clientKeyStore, passwordCharArray);
    return keyManagerFactory;
}