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:it.cnr.icar.eric.server.security.authentication.AuthenticationServiceImpl.java

/**
 * This method is used to remove a certificate from the server keystore.
 * This is called, for example, when a rim:User has been deleted and the
 * User's credentials need to be cleared from the server keystore
 * /*from   w w w  . ja  va2s  .c  o m*/
 * @param alias
 *            A java.lang.String that contains the alias of the public key
 *            credential
 */
public void deleteUserCertificate(String alias) throws RegistryException {
    KeyStore keyStore = getKeyStore();
    java.io.FileOutputStream fos = null;
    try {
        String keystoreFile = getKeyStoreFileName();
        synchronized (keyStoreWriteLock) {
            fos = new java.io.FileOutputStream(keystoreFile);
            keyStore.deleteEntry(alias);
            String keystorePass = getKeyStorePassword();
            keyStore.store(fos, keystorePass.toCharArray());
            fos.flush();
            this.keyStore = null;
        }
    } catch (Throwable t) {
        throw new RegistryException(t);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException io) {
                fos = null;
            }
        }
    }
}

From source file:org.springframework.security.ldap.server.ApacheDsSSLContainer.java

public File getKeystore(File directory) throws Exception {

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);//from  w w w . j a  v  a2  s. c  o  m

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(keysize);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    X509Certificate[] chain = {
            getSelfCertificate(new X500Name(commonName, organizationalUnit, organization, city, state, country),
                    new Date(), (long) validity * 24 * 60 * 60, keyPair, "SHA256withRSA") };
    keyStore.setKeyEntry(alias, keyPair.getPrivate(), keyPass, chain);

    String keystoreName = "ldap.keystore";
    File keystore = new File(directory, keystoreName);
    if (!keystore.createNewFile()) {
        throw new FileNotFoundException("Unable to create file:" + keystore);
    }
    keyStore.store(new FileOutputStream(keystore, false), keyPass);
    return keystore;
}

From source file:org.texai.x509.X509Utils.java

/** Finds or creates the jceks keystore specified by the given path.
 *
 * @param filePath the file path to the keystore
 * @param password the keystore password
 * @return the keystore//w ww .  j a v a2 s  .c  o m
 * @throws KeyStoreException if no Provider supports a KeyStoreSpi implementation for the specified type
 * @throws IOException if there is an I/O or format problem with the keystore data,
 * if a password is required but not given, or if the given password was incorrect
 * @throws NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found
 * @throws CertificateException if any of the certificates in the keystore could not be loaded
 * @throws NoSuchProviderException if the cryptography provider cannot be found
 */
public static KeyStore findOrCreateJceksKeyStore(final String filePath, final char[] password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        NoSuchProviderException {
    //Preconditions
    assert filePath != null : "filePath must not be null";
    assert filePath.endsWith(".jceks") : "file extension must be .jceks";
    assert password != null : "password must not be null";
    assert password.length > 0 : "password must not be empty";

    final File keyStoreFile = new File(filePath);
    final KeyStore keyStore = KeyStore.getInstance("JCEKS");
    if (keyStoreFile.exists()) {
        try (final FileInputStream keyStoreInputStream = new FileInputStream(keyStoreFile)) {
            keyStore.load(keyStoreInputStream, password);
        }
    } else {
        keyStore.load(null, null);
        try (final FileOutputStream keyStoreOutputStream = new FileOutputStream(keyStoreFile)) {
            keyStore.store(keyStoreOutputStream, password);
        }
    }
    return keyStore;
}

From source file:org.texai.x509.X509Utils.java

/** Finds or creates the BKS keystore specified by the given path.
 *
 * @param filePath the file path to the keystore, having the .bks extension
 * @param password the keystore password
 * @return the keystore/*  w w w  .j av a  2 s  .  c  o  m*/
 * @throws KeyStoreException if no Provider supports a KeyStoreSpi implementation for the specified type
 * @throws IOException if there is an I/O or format problem with the keystore data,
 * if a password is required but not given, or if the given password was incorrect
 * @throws NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found
 * @throws CertificateException if any of the certificates in the keystore could not be loaded
 * @throws NoSuchProviderException if the cryptography provider cannot be found
 */
public static KeyStore findOrCreateBKSKeyStore(final String filePath, final char[] password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        NoSuchProviderException {
    //Preconditions
    assert filePath != null : "filePath must not be null";
    assert filePath.endsWith(".bks") : "file extension must be .bks";
    assert password != null : "password must not be null";
    assert password.length > 0 : "password must not be empty";

    final File keyStoreFile = new File(filePath);
    final KeyStore keyStore;
    keyStore = KeyStore.getInstance("BKS");
    if (keyStoreFile.exists()) {
        try (final FileInputStream fileInputStream = new FileInputStream(keyStoreFile)) {
            keyStore.load(fileInputStream, password);
        }
    } else {
        keyStore.load(null, null);
        try (final FileOutputStream fileOutputStream = new FileOutputStream(keyStoreFile)) {
            keyStore.store(fileOutputStream, password);
        }
    }
    return keyStore;
}

From source file:org.texai.x509.X509Utils.java

/** Finds or creates the JKS keystore specified by the given path.
 *
 * @param filePath the file path to the keystore, having the .jks extension
 * @param password the keystore password
 * @return the keystore//from   ww  w.j a v a  2 s. c  o m
 * @throws KeyStoreException if no Provider supports a KeyStoreSpi implementation for the specified type
 * @throws IOException if there is an I/O or format problem with the keystore data,
 * if a password is required but not given, or if the given password was incorrect
 * @throws NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found
 * @throws CertificateException if any of the certificates in the keystore could not be loaded
 * @throws NoSuchProviderException if the cryptography provider cannot be found
 */
public static KeyStore findOrCreateJKSKeyStore(final String filePath, final char[] password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        NoSuchProviderException {
    //Preconditions
    assert filePath != null : "filePath must not be null";
    assert filePath.endsWith(".jks") : "file extension must be .jks";
    assert password != null : "password must not be null";
    assert password.length > 0 : "password must not be empty";

    final File keyStoreFile = new File(filePath);
    final KeyStore keyStore;
    keyStore = KeyStore.getInstance("JKS");
    if (keyStoreFile.exists()) {
        try (final FileInputStream fileInputStream = new FileInputStream(keyStoreFile)) {
            keyStore.load(fileInputStream, password);
        }
    } else {
        keyStore.load(null, null);
        try (final FileOutputStream fileOutputStream = new FileOutputStream(keyStoreFile)) {
            keyStore.store(fileOutputStream, password);
        }
    }
    return keyStore;
}

From source file:org.texai.x509.X509Utils.java

/** Finds or creates the uber keystore specified by the given path.
 *
 * @param filePath the file path to the keystore
 * @param password the keystore password
 * @return the keystore//from  ww w  .jav  a 2  s. c  o m
 * @throws KeyStoreException if no Provider supports a KeyStoreSpi implementation for the specified type
 * @throws IOException if there is an I/O or format problem with the keystore data,
 * if a password is required but not given, or if the given password was incorrect
 * @throws NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found
 * @throws CertificateException if any of the certificates in the keystore could not be loaded
 * @throws NoSuchProviderException if the cryptography provider cannot be found
 */
public static KeyStore findOrCreateUberKeyStore(final String filePath, final char[] password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        NoSuchProviderException {
    //Preconditions
    assert filePath != null : "filePath must not be null";
    assert filePath.endsWith(".uber") : "file extension must be .uber";
    assert isJCEUnlimitedStrengthPolicy() : "JCE unlimited strength policy file must be installed";
    assert password != null : "password must not be null";
    assert password.length > 0 : "password must not be empty";

    final File keyStoreFile = new File(filePath);
    final KeyStore keyStore = KeyStore.getInstance("UBER", BOUNCY_CASTLE_PROVIDER);
    if (keyStoreFile.exists()) {
        try (final FileInputStream keyStoreInputStream = new FileInputStream(keyStoreFile)) {
            keyStore.load(keyStoreInputStream, password);
        }
    } else {
        keyStore.load(null, null);
        try (final FileOutputStream keyStoreOutputStream = new FileOutputStream(keyStoreFile)) {
            keyStore.store(keyStoreOutputStream, password);
        }
    }
    return keyStore;
}

From source file:org.openanzo.security.keystore.SecretKeyStore.java

/**
 * Loads the secret key to use for encryption and decryption. It will read the key from the keystore if it exists. Otherwise it will create a new randomly
 * generated key and save it in a keystore at the given file. It will use the algorithm defined in the <code>algorithm</code> member.
 * /*from  w ww  .ja  v a 2s  .  c o  m*/
 * @param keyStoreStream
 *            stream from which to read the keystore which holds the secret key. If null, a new keystore is created.
 * @param password
 *            password used to protect the and integrity-check the secret key.
 * @param keyStoreDestination
 *            File path to which to save the keystore in case it is newly created or a new key was added. If null, then nothing is written out.
 * @return the loaded or newly generated secret key.
 * @throws AnzoException
 */
private SecretKey loadKey(InputStream keyStoreStream, String password, File keyStoreDestination,
        String keystoreType) throws AnzoException {

    try {
        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(keyStoreStream, password.toCharArray());

        Key key = null;
        if (keyStore.containsAlias(KEY_NAME)) {
            key = keyStore.getKey(KEY_NAME, password.toCharArray());
        } else {
            log.warn("Could not find key '{}' within keystore. Generating a new key.", KEY_NAME);
            KeyGenerator kgen = KeyGenerator.getInstance(algorithm);
            key = kgen.generateKey();
            keyStore.setKeyEntry(KEY_NAME, key, password.toCharArray(), new Certificate[0]);
            if (keyStoreDestination != null) {
                log.warn("Storing new key in the keystore.");
                OutputStream outputStream = null;
                try {
                    outputStream = FileUtils.openOutputStream(keyStoreDestination);
                    keyStore.store(outputStream, password.toCharArray());
                } finally {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                }

            }
        }

        if (!(key instanceof SecretKey))
            throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR,
                    "key must be of type SecretKey: " + key);
        return (SecretKey) key;
    } catch (GeneralSecurityException e) {
        throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR, e);
    } catch (IOException e) {
        throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR, e);
    }

}

From source file:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java

public static void addCertificate(CertificateInfo info, File file) throws PhrescoException {
    char[] passphrase = "changeit".toCharArray();
    InputStream inputKeyStore = null;
    OutputStream outputKeyStore = null;
    try {/*w w w. j  av a 2  s  . c o m*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        keyStore.setCertificateEntry(info.getDisplayName(), info.getCertificate());
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        outputKeyStore = new FileOutputStream(file);
        keyStore.store(outputKeyStore, passphrase);
    } catch (Exception e) {
        throw new PhrescoException(e);
    } finally {
        Utility.closeStream(inputKeyStore);
        Utility.closeStream(outputKeyStore);
    }
}

From source file:org.objectweb.proactive.extensions.ssl.KeyStoreCreator.java

private boolean update(String keyStore) {
    // Load the keystore
    FileInputStream fis = null;/*w  w  w . ja v a2  s.  c  om*/
    try {
        fis = new FileInputStream(keyStore);
    } catch (FileNotFoundException e) {
        System.err.println("Failed to open the key store: " + e);
        return false;
    }

    KeyStore ks = null;
    try {
        ks = KeyStore.getInstance("PKCS12", SslHelpers.BC_NAME);
        ks.load(fis, SslHelpers.DEFAULT_KS_PASSWD.toCharArray());
    } catch (Exception e) {
        System.err.println("Failed to open the key store: " + e);
        return false;
    }

    try {
        // Create a certificate
        CertificateGenerator gen = new CertificateGenerator();
        KeyPair pair = gen.generateRSAKeyPair();
        X509Certificate cert = gen.generateCertificate(SslHelpers.DEFAULT_SUBJET_DN, pair);

        // Remove the old certificate if needed
        try {
            ks.deleteEntry(SslHelpers.DEFAULT_SUBJET_DN);
        } catch (KeyStoreException e) {
            // OK
        }

        // Add the certificate
        ks.setCertificateEntry(SslHelpers.DEFAULT_SUBJET_DN, cert);
        // Write the keystore
        FileOutputStream fos = new FileOutputStream(new File(keyStore));
        ks.store(fos, SslHelpers.DEFAULT_KS_PASSWD.toCharArray());
        fos.close();
        return true;
    } catch (Exception e) {
        System.err.println("Failed to update the keystore " + keyStore + ": " + e);
        return false;
    }
}

From source file:org.texai.x509.X509Utils.java

/** Adds an entry to the specified keystore, creating the keystore if it does not already exist.
 *
 * @param keyStoreFilePath the file path to the keystore
 * @param keyStorePassword the keystore's password
 * @param alias the entry alias//from   ww  w  . j  a  v a2  s.c om
 * @param certPath the certificate path to add
 * @param privateKey the private key associated with the first certificate in the path
 * @return the keystore
 * @throws KeyStoreException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws NoSuchProviderException
 */
public static KeyStore addEntryToKeyStore(final String keyStoreFilePath, final char[] keyStorePassword,
        final String alias, final CertPath certPath, final PrivateKey privateKey) throws KeyStoreException,
        IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException {
    //Preconditions
    assert keyStoreFilePath != null : "keyStoreFilePath must not be null";
    assert !keyStoreFilePath.isEmpty() : "keyStoreFilePath must not be empty";
    assert keyStorePassword != null : "keyStorePassword must not be null";
    assert alias != null : "alias must not be null";
    assert !alias.isEmpty() : "alias must not be empty";

    final KeyStore keyStore = X509Utils.findOrCreateKeyStore(keyStoreFilePath, keyStorePassword);
    final Certificate[] certificateChain = new Certificate[certPath.getCertificates().size() + 1];
    for (int i = 0; i < certPath.getCertificates().size(); i++) {
        certificateChain[i] = certPath.getCertificates().get(i);
    }
    certificateChain[certPath.getCertificates().size()] = X509Utils.getRootX509Certificate();
    keyStore.setKeyEntry(alias, privateKey, keyStorePassword, certificateChain);
    keyStore.store(new FileOutputStream(keyStoreFilePath), keyStorePassword);

    //Postconditions
    assert keyStore != null : "keyStore must not be null";

    return keyStore;
}