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.signserver.server.cryptotokens.KeystoreCryptoTokenTest.java

private void setCMSSignerPropertiesCombined(final int workerId, boolean autoActivate) throws Exception {
    // Create keystore
    keystoreFile = File.createTempFile(KEYSTORE_NAME, ".p12");
    FileOutputStream out = null;// ww  w.  ja v  a2  s  . c  o m
    try {
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        ks.load(null, null);
        out = new FileOutputStream(keystoreFile);
        ks.store(out, pin.toCharArray());
    } finally {
        IOUtils.closeQuietly(out);
    }

    // Setup worker
    globalSession.setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WORKER" + workerId + ".CLASSPATH",
            "org.signserver.module.cmssigner.CMSSigner");
    globalSession.setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WORKER" + workerId + ".SIGNERTOKEN.CLASSPATH",
            KeystoreCryptoToken.class.getName());
    workerSession.setWorkerProperty(workerId, "NAME", "CMSSignerP12");
    workerSession.setWorkerProperty(workerId, "KEYSTORETYPE", "PKCS12");
    workerSession.setWorkerProperty(workerId, "AUTHTYPE", "NOAUTH");
    workerSession.setWorkerProperty(workerId, "KEYSTOREPATH", keystoreFile.getAbsolutePath());
    workerSession.setWorkerProperty(workerId, "DEFAULTKEY", SIGN_KEY_ALIAS);
    if (autoActivate) {
        workerSession.setWorkerProperty(workerId, "KEYSTOREPASSWORD", pin);
    } else {
        workerSession.removeWorkerProperty(workerId, "KEYSTOREPASSWORD");
    }
}

From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java

/**
 * Creates a JKS keystore and imports the specified certificate chain
 *
 * @param ksFileName The full path/name of the keystore to create
 * @param alias The alias for the certificate entry to create
 * @param password The password for the keystore and also the private key
 * @param caBean CABean instance from a call to createSignedCertificateChain
 *//*  w  w w  .j  av  a2  s  . c o m*/
private void createKeystoreWithChain(String ksFileName, String alias, String password, CABean caBean) {
    try {
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(null, null);
        ks.setKeyEntry(alias, caBean.getCSRPrivateKey(), password.toCharArray(), caBean.getChain());
        ks.store(new FileOutputStream(ksFileName), password.toCharArray());
    } catch (Exception e) {
        logger.error(e);
    }
}

From source file:org.signserver.server.cryptotokens.KeystoreCryptoTokenTest.java

private void setCMSSignerPropertiesSeparateToken(final int workerId, final int tokenId, boolean autoActivate)
        throws Exception {
    // Create keystore
    keystoreFile = File.createTempFile(KEYSTORE_NAME, ".p12");
    FileOutputStream out = null;/*from  w w w. j a v a2s.c  om*/
    try {
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        ks.load(null, null);
        out = new FileOutputStream(keystoreFile);
        ks.store(out, pin.toCharArray());
    } finally {
        IOUtils.closeQuietly(out);
    }

    // Setup crypto token
    globalSession.setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WORKER" + tokenId + ".CLASSPATH",
            "org.signserver.server.signers.CryptoWorker");
    globalSession.setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WORKER" + tokenId + ".SIGNERTOKEN.CLASSPATH",
            KeystoreCryptoToken.class.getName());
    workerSession.setWorkerProperty(tokenId, "NAME", "TestCryptoTokenP12");
    workerSession.setWorkerProperty(tokenId, "KEYSTORETYPE", "PKCS12");
    workerSession.setWorkerProperty(tokenId, "KEYSTOREPATH", keystoreFile.getAbsolutePath());
    workerSession.setWorkerProperty(tokenId, "DEFAULTKEY", SIGN_KEY_ALIAS);
    if (autoActivate) {
        workerSession.setWorkerProperty(tokenId, "KEYSTOREPASSWORD", pin);
    } else {
        workerSession.removeWorkerProperty(workerId, "KEYSTOREPASSWORD");
    }

    // Setup worker
    globalSession.setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WORKER" + workerId + ".CLASSPATH",
            "org.signserver.module.cmssigner.CMSSigner");
    workerSession.setWorkerProperty(workerId, "NAME", "CMSSignerP12");
    workerSession.setWorkerProperty(workerId, "AUTHTYPE", "NOAUTH");
    workerSession.setWorkerProperty(workerId, "CRYPTOTOKEN", "TestCryptoTokenP12");
    workerSession.setWorkerProperty(workerId, "DEFAULTKEY", SIGN_KEY_ALIAS);
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public byte[] convertKeystoreByteArray(KeyStore keyStore, String keyStorePassphrase) throws CryptoException {
    byte[] keyStoreBytes;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {//from w  w w.j  a  v a  2 s.  c om
        keyStore.store(outputStream, keyStorePassphrase.toCharArray());

        keyStoreBytes = outputStream.toByteArray();
        return keyStoreBytes;
    } catch (KeyStoreException e) {
        this.logger.error("KeyStoreException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        this.logger.error("NoSuchAlgorithmException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (CertificateException e) {
        this.logger.error("CertificateException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (IOException e) {
        this.logger.error("IOException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } finally {
        try {
            outputStream.close();
        } catch (IOException e) {
            this.logger.error("IOException thrown in finally, " + e.getLocalizedMessage());
            this.logger.debug(e.toString());
        }
    }
}

From source file:org.oscarehr.sharingcenter.actions.SecurityInfrastructureServlet.java

private String deleteInfrastructure(Integer id) {

    InfrastructureDao dao = SpringUtils.getBean(InfrastructureDao.class);
    InfrastructureDataObject toDelete = dao.getInfrastructure(id);

    // there is a problem if the alias is null..
    if (toDelete.getAlias() == null) {
        dao.remove(id);/*from  w w  w . j a  va2  s.  co  m*/
        return "delete";
    }

    //Preparing for the KeyStore containsAlias() test
    OscarProperties oscarProperties = OscarProperties.getInstance();
    String keyStoreFile = oscarProperties.getProperty("TOMCAT_KEYSTORE_FILE");
    String trustStoreFile = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_FILE");
    String keyStorePass = oscarProperties.getProperty("TOMCAT_KEYSTORE_PASSWORD");
    String trustStorePass = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_PASSWORD");

    String alias = toDelete.getAlias();

    KeyStore ks = null;
    KeyStore ts = null;

    try {

        ks = SslUtility.loadKeyStore(keyStoreFile, keyStorePass.toCharArray());
        ts = SslUtility.loadKeyStore(trustStoreFile, trustStorePass.toCharArray());

        if (ks.containsAlias(alias)) {
            ks.deleteEntry(alias);
            ts.deleteEntry(alias);
        }

        // save the keystore
        ks.store(new FileOutputStream(keyStoreFile), keyStorePass.toCharArray());
        // save the truststore
        ts.store(new FileOutputStream(trustStoreFile), trustStorePass.toCharArray());

    } catch (SslException ex) {
        LOGGER.info(ex);
    } catch (KeyStoreException ex) {
        LOGGER.info(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOGGER.info(ex);
    } catch (CertificateException ex) {
        LOGGER.info(ex);
    } catch (FileNotFoundException ex) {
        LOGGER.info(ex);
    } catch (IOException ex) {
        LOGGER.info(ex);
    }

    dao.remove(id);

    return "delete";

}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public void serializeKeyStore(KeyStore keyStore, String keyStorePassphrase, String filename)
        throws CryptoException {
    FileOutputStream fos = null;//from  w ww .j  a  va  2s .c om
    try {
        fos = new FileOutputStream(filename);
        keyStore.store(fos, keyStorePassphrase.toCharArray());
    } catch (FileNotFoundException e) {
        this.logger.error(e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (KeyStoreException e) {
        this.logger.error(e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        this.logger.error(e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (CertificateException e) {
        this.logger.error(e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (IOException e) {
        this.logger.error(e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } finally {
        if (fos != null) {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                this.logger.error(e.getLocalizedMessage());
                this.logger.debug(e.toString());
                throw new CryptoException(e.getLocalizedMessage(), e);
            }
        }
    }
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private synchronized void deleteFromStore(String alias, String path, String pass, KeyStore store) {
    if (alias == null) {
        throw new IllegalArgumentException("Alias cannot be null.");
    }// w  ww . j  a  va2s  .  c o  m
    File storeFile = new File(path);
    try (FileOutputStream fos = new FileOutputStream(storeFile)) {
        store.deleteEntry(alias);
        store.store(fos, pass.toCharArray());
    } catch (KeyStoreException | IOException | CertificateException | NoSuchAlgorithmException e) {
        LOGGER.error("Unable to remove entry {} from store", alias, e);
    }
}

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 {//from  ww  w  .j a va 2  s  .c  om
        // 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.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java

private void storeKeyToKeyStore(String alias, Key cryptoKey, Certificate certInCertChain) {
    KeyStore keyStore;
    try {/*  ww w  .  j  a  v a  2s.c  o  m*/
        keyStore = KeyStore.getInstance(AgentConstants.DEVICE_KEYSTORE_TYPE);
        Certificate[] certChain = new Certificate[1];
        certChain[0] = certInCertChain;

        keyStore.setKeyEntry(alias, cryptoKey, AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray(),
                certChain);
        keyStore.store(new FileOutputStream(AgentConstants.DEVICE_KEYSTORE),
                AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray());

    } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
        log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst trying to store the key with alias "
                + "[" + alias + "] in the device keystore.");
        log.error(AgentConstants.LOG_APPENDER + e);
        log.warn(AgentConstants.LOG_APPENDER + "Key [" + alias + "] was not stored in the keystore; "
                + "Hence the device will be re-enrolled during next restart.");
    }
}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

/**
 * Return the file's absolute path name string
 * /* www.  j  a v a  2s  .  c o  m*/
 * @param x509Cert
 * @return Path name string
 * @throws Exception
 */
public static String importCertificate(String x509Cert) throws Exception {
    // CREATE A KEYSTORE OF TYPE "Java Key Store"
    KeyStore ks = KeyStore.getInstance("JKS");
    /*
     * LOAD THE STORE The first time you're doing this (i.e. the keystore
     * does not yet exist - you're creating it), you HAVE to load the
     * keystore from a null source with null password. Before any methods
     * can be called on your keystore you HAVE to load it first. Loading it
     * from a null source and null password simply creates an empty
     * keystore. At a later time, when you want to verify the keystore or
     * get certificates (or whatever) you can load it from the file with
     * your password.
     */
    ks.load(null, null);
    // GET THE FILE CONTAINING YOUR CERTIFICATE
    File x509 = new File(x509Cert);
    FileInputStream fis = new FileInputStream(x509);
    BufferedInputStream bis = new BufferedInputStream(fis);
    // I USE x.509 BECAUSE THAT'S WHAT keytool CREATES
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // NOTE: THIS IS java.security.cert.Certificate NOT
    // java.security.Certificate
    X509Certificate cert = (X509Certificate) cf.generateCertificate(bis);

    ks.setCertificateEntry(CERT_ALIAS, cert);
    // SAVE THE KEYSTORE TO A FILE
    /*
     * After this is saved, I believe you can just do setCertificateEntry to
     * add entries and then not call store. I believe it will update the
     * existing store you load it from and not just in memory.
     */
    File storeFile = new File(x509.getParentFile().getAbsolutePath(), KEYSTORE);
    ks.store(new FileOutputStream(storeFile), KEYSTORE_PASS.toCharArray());

    return storeFile.getAbsolutePath();
}