Example usage for java.security KeyStore setEntry

List of usage examples for java.security KeyStore setEntry

Introduction

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

Prototype

public final void setEntry(String alias, Entry entry, ProtectionParameter protParam) throws KeyStoreException 

Source Link

Document

Saves a keystore Entry under the specified alias.

Usage

From source file:net.link.util.common.KeyUtils.java

public static KeyStore addEntry(KeyStore keyStore, KeyStore.Entry entry, char[] keyEntryPassword,
        String alias) {/*from www .jav a2 s .  co  m*/

    try {
        keyStore.setEntry(alias, entry, new KeyStore.PasswordProtection(keyEntryPassword));

        return keyStore;
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException(
                String.format("could not set new entry on keystore for alias: %s", alias), e);
    }
}

From source file:com.oneis.common.utils.SSLCertificates.java

public static SSLContext load(String keysDirectory, String certsName, String clientCAName, boolean quiet)
        throws Exception {
    // For some indiciation of what's going on early in the boot process
    if (!quiet) {
        System.out.println("Loading " + certsName + " SSL certificates from " + keysDirectory);
    }/* w w  w .  j  a v a2 s  . c  o  m*/

    // Get filenames
    String keyPathname = keysDirectory + "/" + certsName + ".key";
    String certPathname = keysDirectory + "/" + certsName + ".crt";
    final String intermediateCertPathnameBase = keysDirectory + "/" + certsName + "-intermediate";
    String clientCAPathname = null;
    if (clientCAName != null) {
        clientCAPathname = keysDirectory + "/" + clientCAName + ".crt";
    }

    if (!new File(keyPathname).exists()) {
        System.out.println("Doesn't exist: " + keyPathname);
        return null;
    }
    if (!new File(certPathname).exists()) {
        System.out.println("Doesn't exist: " + certPathname);
        return null;
    }
    if (clientCAPathname != null) {
        if (!new File(clientCAPathname).exists()) {
            System.out.println("Doesn't exist: " + clientCAPathname);
            return null;
        }
    }

    char[] nullPassword = {};

    PrivateKey privateKey = readPEMPrivateKey(keyPathname);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // Server certificate
    ArrayList<java.security.cert.Certificate> certList = new ArrayList<java.security.cert.Certificate>(4);
    java.security.cert.Certificate cert = cf.generateCertificate(readPEM(certPathname));
    certList.add(cert);
    // Optional intermediate certificates
    int intermediateCounter = 1;
    while (true) {
        String intermediateCertPathname = intermediateCertPathnameBase;
        if (intermediateCounter != 1) {
            intermediateCertPathname += "-" + intermediateCounter;
        }
        intermediateCounter++;
        intermediateCertPathname += ".crt";
        if (new File(intermediateCertPathname).exists()) {
            certList.add(cf.generateCertificate(readPEM(intermediateCertPathname)));
        } else {
            // End of cert list
            break;
        }
    }
    // Optional client CA certificate
    java.security.cert.Certificate clientCACert = null;
    if (clientCAPathname != null) {
        clientCACert = cf.generateCertificate(readPEM(clientCAPathname));
    }
    if (clientCAName != null && clientCACert == null) {
        throw new RuntimeException("Logic error, failed to load client CA cert when required");
    }

    KeyStore ks = KeyStore.getInstance("JKS", "SUN");
    ks.load(null, nullPassword);
    ks.setKeyEntry("ONEIS", (Key) privateKey, "".toCharArray(),
            certList.toArray(new java.security.cert.Certificate[certList.size()]));

    if (clientCACert != null) {
        KeyStore.TrustedCertificateEntry tce = new KeyStore.TrustedCertificateEntry(clientCACert);
        ks.setEntry("CLIENTCA", tce, null);
    }

    // Generate some random Java API stuff, just for entertainment
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, nullPassword);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    if (!quiet) {
        System.out.println(" - server cert chain length " + certList.size()
                + (clientCACert != null ? ", requires client cert" : ", public server"));
    }
    return sslContext;
}

From source file:gov.niem.ws.util.SecurityUtil.java

public static KeyManager[] createKeyManagers(KeyPair clientKey, X509Certificate clientCert)
        throws GeneralSecurityException, IOException {
    // Create a new empty key store.
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);/*  ww  w  .  jav a2s .co m*/

    Certificate[] chain = { clientCert };

    // The KeyStore requires a password for key entries.
    char[] password = { ' ' };

    // Since we never write out the key store, we don't bother protecting
    // the key.
    ks.setEntry("client-key", new KeyStore.PrivateKeyEntry(clientKey.getPrivate(), chain),
            new KeyStore.PasswordProtection(password));

    // Shove the key store in a KeyManager.
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, password);
    return kmf.getKeyManagers();
}

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

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    try {/*from  w  w w .  j  a va  2  s  . c  om*/
        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:com.shekhargulati.reactivex.docker.client.ssl.DockerCertificates.java

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new DockerCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }//w  w  w  .  j ava 2 s  .c o  m

    try {
        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, KEY_STORE_PASSWORD);
        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:com.shekhargulati.reactivex.rxokhttp.SslCertificates.java

private SslCertificates(final Builder builder) throws SslCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new SslCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }/*from   w w w. j av a  2 s  .  c om*/

    try {
        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, KEY_STORE_PASSWORD);
        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 (java.security.cert.CertificateException | IOException | NoSuchAlgorithmException
            | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException
            | KeyManagementException e) {
        throw new SslCertificateException(e);
    }
}

From source file:energy.usef.environment.tool.security.KeystoreService.java

/**
 * Creates a NaCl secret key in the local key store ( {@link Config#USEF_HOME_FOLDER} / {@link Config#USEF_CONFIGURATION_FOLDER}
 * / {@link Config#KEYSTORE_FILENAME}). Creates the key store if it does not exist.
 *
 * @param seed Password//from   w  ww .ja  v a  2s  .  c o m
 * @return the associate public key.
 */
public byte[] createSecretKey(String seed) {
    if (seed == null) {
        throw new IllegalArgumentException("A seed must be provided in order to create keys!");
    }

    byte[] publicKey = new byte[32];
    byte[] privateKey = new byte[64];

    NaCl.sodium().crypto_sign_ed25519_seed_keypair(publicKey, privateKey, seed.getBytes(UTF_8));
    SecretKey secretKey = new SecretKeySpec(privateKey, ALGORITHM);

    char[] ksPassword = toCharArray(keystorePassword);
    char[] ksKeyPassword = toCharArray(keystorePKPassword);

    try {
        createNewStoreIfNeeded(keystoreFilename, ksPassword);
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    try (InputStream is = new FileInputStream(keystoreFilename)) {
        KeyStore ks = KeyStore.getInstance(JCEKS);
        ks.load(is, ksPassword);

        SecretKeyEntry secretKeyEntry = new SecretKeyEntry(secretKey);
        ProtectionParameter protectionParameter = new KeyStore.PasswordProtection(ksKeyPassword);

        ks.setEntry(keystorePKAlias, secretKeyEntry, protectionParameter);
        try (OutputStream os = new FileOutputStream(keystoreFilename)) {
            ks.store(os, ksPassword);
        }

    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
        throw new RuntimeException(e);
    }
    return publicKey;
}

From source file:talkeeg.httpserver.HttpServer.java

private NHttpConnectionFactory<DefaultNHttpServerConnection> createConnectionFactory() {
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (config.isUseTLS()) {
        try {/*from www  .j a v  a 2  s . c  o  m*/
            KeyStore keystore = KeyStore.getInstance("jks");
            char[] password = new char[0];
            keystore.load(null, password);
            final X509Certificate certificate = certManager.getCertificate(OwnedKeyType.USER);
            KeyStore.PrivateKeyEntry entry = new KeyStore.PrivateKeyEntry(
                    ownedKeysManager.getPrivateKey(OwnedKeyType.USER), new Certificate[] { certificate });

            keystore.setEntry("", entry, new KeyStore.PasswordProtection(password));
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keystore, password);
            final KeyManager[] keymanagers = kmfactory.getKeyManagers();
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(keymanagers, null, null);
            connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, ConnectionConfig.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException("Can not initialise SSL.", e);
        }
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT);
    }
    return connFactory;
}

From source file:org.opcfoundation.ua.transport.https.HttpsSettings.java

/**
 * Set keypair of a https application. This replaces a keyManager.
 * Additional CA certifications can be attached. 
 * /*from ww w. j ava  2 s. c  o m*/
 * @param keypair
 * @param caCerts
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 */
public void setKeyPair(KeyPair keypair, Cert... caCerts) {
    if (keypair != null)
        try {
            KeyStore keystore = KeyStore.getInstance("jks");
            Certificate[] certs = new Certificate[] { keypair.certificate.certificate };
            PrivateKeyEntry entry = new PrivateKeyEntry(keypair.privateKey.getPrivateKey(), certs);
            String password = "";
            keystore.load(null);
            keystore.setEntry("myentry-" + keypair.hashCode(), entry,
                    new PasswordProtection(password.toCharArray()));
            int count = caCerts.length;
            for (int i = 0; i < count; i++) {
                String id = "cacert-" + (i + 1);
                keystore.setEntry(id, new TrustedCertificateEntry(caCerts[i].certificate), null);
            }
            setKeyStore(keystore, "");
        } catch (KeyStoreException e) {
            // Expected if JKS is not available (e.g. in Android)

        } catch (NoSuchAlgorithmException e) {
            // Unexpected
            throw new RuntimeException(e);
        } catch (CertificateException e) {
            // Unexpected
            throw new RuntimeException(e);
        } catch (IOException e) {
            // Unexpected
            throw new RuntimeException(e);
        } catch (ServiceResultException e) {
            // Unexpected
            throw new RuntimeException(e);
        }
}

From source file:com.streamsets.datacollector.credential.javakeystore.JavaKeyStoreCredentialStore.java

public void storeCredential(String name, String credential) {
    Utils.checkNotNull(name, "name cannot be NULL");
    Utils.checkNotNull(credential, "credential cannot be NULL");

    try {/*from   w ww. j a  v a  2 s. co m*/
        KeyStore keyStore = loadKeyStore();
        if (keyStore == null) {
            keyStore = createKeyStore();
        }
        // the keystore does not check the length of the KEY whe adding a AES key,
        // so we just put the credential as AES key payload.
        SecretKey secret = new SecretKeySpec(credential.getBytes("UTF-8"), "AES");

        keyStore.setEntry(name, new KeyStore.SecretKeyEntry(secret),
                new KeyStore.PasswordProtection(getKeystorePassword().toCharArray()));

        persistStore(keyStore);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}