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.tolven.gatekeeper.CertificateHelper.java

public static byte[] toByteArray(KeyStore keyStore, char[] password) {
    ByteArrayOutputStream baos = null;
    try {/*from  w w  w  . ja  v  a 2 s .  c  o m*/
        baos = new ByteArrayOutputStream();
        try {
            keyStore.store(baos, password);
        } catch (Exception ex) {
            throw new RuntimeException("Could not store keystore", ex);
        }
        byte[] byteArr = baos.toByteArray();
        return byteArr;
    } finally {
        if (baos != null)
            try {
                baos.close();
            } catch (IOException ex) {
                throw new RuntimeException("Could not close bytearrayoutputstream for keystore", ex);
            }
    }
}

From source file:org.commonjava.ssl.util.KeyStoreManager.java

public static void save(KeyStore keystore, File keystoreFile, char[] storepass, boolean makeBackup)
        throws SSLToolsException {
    OutputStream out = null;/*  w  w  w .ja  v  a 2s.c om*/
    try {
        if (makeBackup && keystoreFile.exists() && !keystoreFile.isDirectory()) {
            File renamed = new File(keystoreFile.getAbsolutePath() + ".bak");
            keystoreFile.renameTo(renamed);
        }

        out = new FileOutputStream(keystoreFile);
        keystore.store(out, storepass);
    } catch (Exception e) {
        throw new SSLToolsException("Failed to write keystore: %s", e, e.getMessage());
    } finally {
        closeQuietly(out);
    }
}

From source file:org.teknux.jettybootstrap.keystore.JettyKeystore.java

private static void saveKeyStore(KeyStore keyStore, File file, String password) throws JettyKeystoreException {
    FileOutputStream fileInputStream = null;

    try {/*www .j  ava  2  s. c om*/
        fileInputStream = new FileOutputStream(file);
        keyStore.store(fileInputStream, password.toCharArray());
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
        throw new JettyKeystoreException(JettyKeystoreException.ERROR_SAVE_KEYSTORE,
                "Can not save keystore file", e);
    } finally {
        if (fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.apache.hadoop.gateway.services.security.impl.X509CertificateUtil.java

public static void writeCertificateToJKS(Certificate cert, final File file)
        throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    char[] password = "changeit".toCharArray();
    ks.load(null, password);//from  w  w  w.  j ava 2s .  c  o m
    ks.setCertificateEntry("gateway-identity", cert);
    FileOutputStream fos = new FileOutputStream(file);
    /* Coverity Scan CID 1361992 */
    try {
        ks.store(fos, password);
    } finally {
        fos.close();
    }
}

From source file:net.link.util.test.pkix.PkiTestUtils.java

/**
 * Persist the given private key and corresponding certificate to a keystore file.
 *
 * @param pkcs12keyStore   The file of the keystore to write the key material to.
 * @param keyStoreType     The type of the key store format to use.
 * @param privateKey       The private key to persist.
 * @param certificate      The X509 certificate corresponding with the private key.
 * @param keyStorePassword The keystore password.
 * @param keyEntryPassword The keyentry password.
 *//*from w w w.ja  v a 2s  .c o m*/
public static KeyStore persistInKeyStore(File pkcs12keyStore, String keyStoreType, PrivateKey privateKey,
        Certificate certificate, String keyStorePassword, String keyEntryPassword)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, keyStorePassword.toCharArray());
    keyStore.setKeyEntry(DEFAULT_ALIAS, privateKey, keyEntryPassword.toCharArray(),
            new Certificate[] { certificate });
    FileOutputStream keyStoreOut = new FileOutputStream(pkcs12keyStore);
    try {
        keyStore.store(keyStoreOut, keyStorePassword.toCharArray());
    } finally {
        keyStoreOut.close();
    }

    return keyStore;
}

From source file:com.blackducksoftware.tools.commonframework.core.encryption.Password.java

/**
 * Generates a new key. Should be used manually and only when creating a new
 * key is necessary. WARNING: If the keys in the KeyStore files are replaced
 * then we will not be able to decrypt passwords that were encrypted with
 * the old keys.// w  w  w .  j a v  a  2s .  c  om
 *
 * @param keypass
 *            char[] with the keypass that will gain access to the key
 *            (currently hard coded in)
 * @throws IOException
 */
@SuppressWarnings("unused")
private static Key setKey(final char[] keypass, final File keyFile) throws Exception {

    Key key = null;
    FileOutputStream output = null;
    try {
        output = new FileOutputStream(keyFile.getCanonicalPath());
        key = KeyGenerator.getInstance(ENCRYPTION_ALGORITHM).generateKey();
        final KeyStore keystore = KeyStore.getInstance(KEYSTORE_TYPE);
        keystore.load(null, null);
        keystore.setKeyEntry(KEY_ALIAS, key, keypass, null);
        keystore.store(output, keypass);
    } finally {
        if (output != null) {
            output.close();
        }
    }

    return key;
}

From source file:org.apache.ofbiz.base.util.KeyStoreUtil.java

public static void storeComponentKeyStore(String componentName, String keyStoreName, KeyStore store)
        throws IOException, GenericConfigException, NoSuchAlgorithmException, CertificateException,
        KeyStoreException {//from   w w  w .ja  v  a 2  s  .  c o  m
    ComponentConfig.KeystoreInfo ks = ComponentConfig.getKeystoreInfo(componentName, keyStoreName);
    File file = FileUtil.getFile(ks.createResourceHandler().getFullLocation());
    FileOutputStream out = new FileOutputStream(file);
    try {
        store.store(out, ks.getPassword().toCharArray());
    } finally {
        out.close();
    }
}

From source file:org.glite.slcs.pki.bouncycastle.Codec.java

/**
 * Stores the private key and certificate in a PKCS12 file. The certificate
 * Subject CN is used as key alias in the PKCS12 store.
 * /*from   w  w  w.ja  va2 s.c o  m*/
 * @param privateKey
 *            The private key.
 * @param certificate
 *            The X509 certificate.
 * @param chain
 *            The X509 certificate chain.
 * @param file
 *            The file object.
 * @param password
 *            The password for the PKCS12 file.
 * @throws GeneralSecurityException
 *             If a crypto error occurs.
 * @throws IOException
 *             If an IO error occurs.
 */
static public void storePKCS12(PrivateKey privateKey, X509Certificate certificate, X509Certificate chain[],
        File file, char[] password) throws GeneralSecurityException, IOException {
    // set the bag information for the PKCS12 keystore
    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privateKey;
    PublicKey publicKey = certificate.getPublicKey();
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifierStructure(publicKey));

    // the PKCS12 keystore key alias is the CN
    String alias = getPrincipalValue(certificate, X509Principal.CN);

    // build full cert chain
    int nCerts = chain.length + 1;
    Certificate certs[] = new Certificate[nCerts];
    certs[0] = certificate;
    for (int i = 0; i < chain.length; i++) {
        certs[i + 1] = chain[i];
    }
    // create a PKCS12 keystore
    KeyStore p12Store = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME);
    p12Store.load(null, null);
    // set the key entry
    p12Store.setKeyEntry(alias, privateKey, null, certs);
    // store the file
    FileOutputStream fos = new FileOutputStream(file);
    p12Store.store(fos, password);
    fos.close();
}

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

/**
 * Persist the given private key and corresponding certificate to a PKCS12 keystore file.
 *
 * @param pkcs12keyStore   the file of the PKCS12 keystore to write the key material to.
 * @param privateKey       the private key to persist.
 * @param certificate      the X509 certificate corresponding with the private key.
 * @param keyStorePassword the keystore password.
 * @param keyEntryPassword the keyentry password.
 *///w w  w  .j a v  a2s  .  c o  m
public static void saveNewKeyStore(File pkcs12keyStore, PrivateKey privateKey, X509Certificate certificate,
        char[] keyStorePassword, char[] keyEntryPassword) {

    try {
        KeyStore keyStore = newKeyStore(privateKey, certificate, keyStorePassword, keyEntryPassword);

        FileOutputStream keyStoreOut = new FileOutputStream(pkcs12keyStore);
        try {

            keyStore.store(keyStoreOut, keyStorePassword);
        } finally {
            keyStoreOut.close();
        }
    } catch (IOException e) {
        throw new InternalInconsistencyException("Key Store can't be created or stored.", e);
    } catch (CertificateException e) {
        throw new InternalInconsistencyException("Certificate couldn't be stored.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new InternalInconsistencyException("KeyStores integrity algorithm not supported.", e);
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException(
                "PKCS12 KeyStores not supported or store does not support the key or certificate.", e);
    }
}

From source file:org.apache.hadoop.hbase.io.crypto.TestKeyStoreKeyProvider.java

@BeforeClass
public static void setUp() throws Exception {
    KEY = MessageDigest.getInstance("SHA-256").digest(ALIAS.getBytes());
    // Create a JKECS store containing a test secret key
    KeyStore store = KeyStore.getInstance("JCEKS");
    store.load(null, PASSWORD.toCharArray());
    store.setEntry(ALIAS, new KeyStore.SecretKeyEntry(new SecretKeySpec(KEY, "AES")),
            new KeyStore.PasswordProtection(PASSWORD.toCharArray()));
    // Create the test directory
    String dataDir = TEST_UTIL.getDataTestDir().toString();
    new File(dataDir).mkdirs();
    // Write the keystore file
    storeFile = new File(dataDir, "keystore.jks");
    FileOutputStream os = new FileOutputStream(storeFile);
    try {/*from   w w  w  . j ava  2s .c  om*/
        store.store(os, PASSWORD.toCharArray());
    } finally {
        os.close();
    }
    // Write the password file
    Properties p = new Properties();
    p.setProperty(ALIAS, PASSWORD);
    passwordFile = new File(dataDir, "keystore.pw");
    os = new FileOutputStream(passwordFile);
    try {
        p.store(os, "");
    } finally {
        os.close();
    }
}