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:dk.itst.oiosaml.sp.IntegrationTests.java

@Before
public final void setUpServer() throws Exception {
    tmpdir = new File(System.getProperty("java.io.tmpdir") + "/oiosaml-" + Math.random());
    tmpdir.mkdir();//from  w w  w .  j  a va 2  s.c o  m
    FileUtils.forceMkdir(new File(tmpdir, "metadata/IdP"));
    FileUtils.forceMkdir(new File(tmpdir, "metadata/SP"));

    credential = TestHelper.getCredential();
    EntityDescriptor idpDescriptor = TestHelper.buildEntityDescriptor(credential);
    FileOutputStream fos = new FileOutputStream(new File(tmpdir, "metadata/IdP/gen.xml"));
    IOUtils.write(XMLHelper.nodeToString(SAMLUtil.marshallObject(idpDescriptor)).getBytes(), fos);
    fos.close();

    EntityDescriptor spDescriptor = (EntityDescriptor) SAMLUtil
            .unmarshallElement(getClass().getResourceAsStream("/dk/itst/oiosaml/sp/SPMetadata.xml"));
    fos = new FileOutputStream(new File(tmpdir, "metadata/SP/SPMetadata.xml"));
    IOUtils.write(XMLHelper.nodeToString(SAMLUtil.marshallObject(spDescriptor)).getBytes(), fos);
    fos.close();

    spMetadata = new SPMetadata(spDescriptor, SAMLConstants.SAML20P_NS);
    idpMetadata = new IdpMetadata(SAMLConstants.SAML20P_NS, idpDescriptor);

    fos = new FileOutputStream(new File(tmpdir, "oiosaml-sp.log4j.xml"));
    IOUtils.write(
            "<!DOCTYPE log4j:configuration SYSTEM \"http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/log4j.dtd\"><log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\" debug=\"false\"></log4j:configuration>",
            fos);
    fos.close();

    Properties props = new Properties();
    props.setProperty(Constants.PROP_CERTIFICATE_LOCATION, "keystore");
    props.setProperty(Constants.PROP_CERTIFICATE_PASSWORD, "password");
    props.setProperty(Constants.PROP_LOG_FILE_NAME, "oiosaml-sp.log4j.xml");
    props.setProperty(SAMLUtil.OIOSAML_HOME, tmpdir.getAbsolutePath());
    props.setProperty(Constants.PROP_SESSION_HANDLER_FACTORY, SingleVMSessionHandlerFactory.class.getName());

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setKeyEntry("oiosaml", credential.getPrivateKey(), "password".toCharArray(),
            new Certificate[] { TestHelper.getCertificate(credential) });
    OutputStream bos = new FileOutputStream(new File(tmpdir, "keystore"));
    ks.store(bos, "password".toCharArray());
    bos.close();

    props.setProperty(Constants.PROP_ASSURANCE_LEVEL, "2");
    props.setProperty(Constants.PROP_IGNORE_CERTPATH, "true");
    fos = new FileOutputStream(new File(tmpdir, "oiosaml-sp.properties"));
    props.store(fos, "Generated");
    fos.close();

    SAMLConfiguration.setSystemConfiguration(null);
    IdpMetadata.setMetadata(null);
    SPMetadata.setMetadata(null);
    System.setProperty(SAMLUtil.OIOSAML_HOME, tmpdir.getAbsolutePath());
    server = new Server(8808);
    WebAppContext wac = new WebAppContext();
    wac.setClassLoader(Thread.currentThread().getContextClassLoader());
    wac.setContextPath("/saml");
    wac.setWar("webapp/");

    server.setHandler(wac);
    server.start();

    client = new WebClient();
    client.setRedirectEnabled(false);
    client.setThrowExceptionOnFailingStatusCode(false);
    handler = new RedirectRefreshHandler();
    client.setRefreshHandler(handler);
}

From source file:com.vmware.bdd.manager.SoftwareManagerCollector.java

/**
 * TODO this method has to be reverted://w w  w  .jav a2 s.  c o m
 * because if the target path is not accessible, it will load cert from the default keystore in java home,
 * but still try to write it to the non accessible path.
 * @param certificate
 * @param keyStorePath
 */
protected static void saveSslCertificate(String certificate, String keyStorePath) {
    Certificate[] certs;
    //parse certificates
    try {
        if (CommonUtil.isBlank(certificate)) {
            throw SoftwareManagerCollectorException.BAD_CERT(null);
        }

        byte[] certBytes = Base64.decodeBase64(certificate.replaceAll("-----BEGIN CERTIFICATE-----", "")
                .replaceAll("-----END CERTIFICATE-----", "").getBytes());

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Collection c = cf.generateCertificates(new ByteArrayInputStream(certBytes));
        certs = new Certificate[c.toArray().length];

        if (c.size() == 0) {
            throw SoftwareManagerCollectorException.BAD_CERT(null);
        } else if (c.size() == 1) {
            certs[0] = cf.generateCertificate(new ByteArrayInputStream(certBytes));
        } else {
            certs = (Certificate[]) c.toArray(certs);
        }
    } catch (CertificateException e) {
        throw SoftwareManagerCollectorException.BAD_CERT(e);
    }

    //load & save keystore
    OutputStream out = null;
    try {
        KeyStore keyStore = CommonUtil.loadAppMgrKeyStore(keyStorePath);
        if (keyStore == null) {
            logger.error(Messages.getString("SW_MGR_COLLECTOR.CANNT_READ_KEYSTORE"));
            throw new SWMgrCollectorInternalException(
                    Messages.getString("SW_MGR_COLLECTOR.CANNT_READ_KEYSTORE"));
        }

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        String md5Fingerprint = "";
        for (Certificate cert : certs) {
            md5.update(cert.getEncoded());
            md5Fingerprint = CommonUtil.toHexString(md5.digest());
            logger.debug("md5 finger print: " + md5Fingerprint);
            logger.debug("added cert: " + cert);
            keyStore.setCertificateEntry(md5Fingerprint, cert);
        }
        out = new FileOutputStream(keyStorePath + Constants.APPMANAGER_KEYSTORE_FILE);
        keyStore.store(new BufferedOutputStream(out), Constants.APPMANAGER_KEYSTORE_PASSWORD);
    } catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException e) {
        logger.error(Messages.getString("SW_MGR_COLLECTOR.FAIL_SAVE_CERT"), e);
        throw new SWMgrCollectorInternalException(e, Messages.getString("SW_MGR_COLLECTOR.FAIL_SAVE_CERT"));
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                logger.warn("Output stream of appmanagers.jks close failed.");
            }
        }
    }
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.KeyStoreReader.java

private synchronized void saveKeyStore(KeyStore keyStore, String configEntryKeyStorePath,
        String configEntryKeyStorePassword) throws KeystoreException {
    FileOutputStream os = null;//from  ww  w. java 2s  . c om
    try {
        os = new FileOutputStream(configEntryKeyStorePath);
        keyStore.store(os, configEntryKeyStorePassword.toCharArray());
    } catch (KeyStoreException e) {
        String errorMsg = "KeyStore issue occurred when loading KeyStore";
        throw new KeystoreException(errorMsg, e);
    } catch (FileNotFoundException e) {
        String errorMsg = "KeyStore file not found when loading KeyStore";
        throw new KeystoreException(errorMsg, e);
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm not found when loading KeyStore";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "CertificateException when loading KeyStore";
        throw new KeystoreException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "Input output issue occurred when loading KeyStore";
        throw new KeystoreException(errorMsg, e);
    } finally {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            log.error("Error closing KeyStore output stream", e);
        }
    }
}

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

protected void writeKeystoreToFile(final KeyStore keyStore, final File file)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    // TODO: backup the keystore on disk before attempting a write and restore on failure
    final FileOutputStream out = new FileOutputStream(file);
    try {/*ww  w.  j ava2  s  . c o  m*/
        keyStore.store(out, masterService.getMasterSecret());
    } finally {
        out.close();
    }
}

From source file:mitm.djigzo.web.pages.certificate.CertificateImportKey.java

private int uploadKeyStore(KeyStore keyStore, KeyAndCertificateWorkflow.MissingKey missingKey, String password)
        throws WebServiceCheckedException, KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException {//from  w w  w  .j  a v a2s.  c o  m
    ByteArrayOutputStream pfx = new ByteArrayOutputStream();

    keyStore.store(pfx, password.toCharArray());

    return keyAndCertificateWorkflowWS.addPFX(pfx.toByteArray(), password, missingKey);
}

From source file:com.evolveum.midpoint.init.ConfigurableProtectorFactory.java

public void init() {
    Configuration config = configuration.getConfiguration(PROTECTOR_CONFIGURATION);
    protectorConfig = new ProtectorConfiguration(config);

    //Extract file if not exists
    if (config.getString("midpoint.home") == null) {
        return;/*from  w  w  w .j av a  2s  .co  m*/
    }

    File ks = new File(protectorConfig.getKeyStorePath());
    if (ks.exists()) {
        return;
    }

    //todo improve
    FileOutputStream fos = null;
    try {
        KeyStore keystore = KeyStore.getInstance("jceks");
        char[] password = "changeit".toCharArray();

        keystore.load(null, password);

        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey secretKey = keyGen.generateKey();

        keystore.setKeyEntry("default", secretKey, "midpoint".toCharArray(), null);

        fos = new FileOutputStream(protectorConfig.getKeyStorePath());
        keystore.store(fos, password);
        fos.close();
    } catch (Exception ex) {
        throw new SystemException("Couldn't generate keystore, reason: " + ex.getMessage(), ex);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

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   ww w .j  a  va  2 s. 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:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java

private void saveKeyStore(KeyStore key_store, File keyStoreFile, String id) throws FileNotFoundException,
        KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    char[] ksPassword = getKsPass(id);

    // write the KeyStore to disk
    FileOutputStream os = new FileOutputStream(keyStoreFile);
    key_store.store(os, ksPassword);
    os.close();/* www  .ja v  a 2  s.  co m*/
}

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

public boolean addCertificate(final String keyStoreName, final String keyStorePwd, final String certificate,
        final String alias) {
    try {//ww  w .jav a2s . c  om
        final X509Certificate newCert = getCertificate(certificate);
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName);
        keyStore.load(fInputStream, keyStorePwd.toCharArray());
        if (keyStore.isCertificateEntry(alias)) {
            keyStore.deleteEntry(alias);
        }
        keyStore.setCertificateEntry(alias, newCert);
        keyStore.store(new FileOutputStream(workingDir + keyStoreName), keyStorePwd.toCharArray());
        LOG.info("Certificate {}  Added to keyStore {}", alias, keyStoreName);
        return true;
    } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException | IOException e) {
        LOG.error("failed to add certificate", e);
        return false;
    }
}

From source file:gov.nih.nci.cacisweb.action.SecureFTPAction.java

/**
 * //from  ww w  .  j a  v  a2  s.  co m
 * @return
 * @throws Exception
 */
public String delete() throws Exception {
    log.debug("delete() - START");
    String secureFTPPropertyFileLocation = CaCISUtil
            .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_PROPERTIES_FILE_LOCATION);
    String secureFTPKeystoreLocation = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation,
            CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_LOCATION_PROP_NAME));
    String secureFTPKeystorePassword = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation,
            CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_PASSWORD_PROP_NAME));
    try {
        CaCISUtil caCISUtil = new CaCISUtil();
        KeyStore keystore = caCISUtil.getKeystore(secureFTPKeystoreLocation,
                CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureFTPKeystorePassword);
        caCISUtil.releaseKeystore();
        // Delete the certificate
        keystore.deleteEntry(secureFTPBean.getCertificateAlias());

        // Save the new keystore contents
        FileOutputStream out = new FileOutputStream(new File(secureFTPKeystoreLocation));
        keystore.store(out, secureFTPKeystorePassword.toCharArray());
        out.close();

        // delete the entry from FTP configuration properties file
        PropertiesConfiguration config = new PropertiesConfiguration(
                CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_CONFIG_FILE_LOCATION));
        config.clearProperty(secureFTPBean.getCertificateAlias());
        config.save();
    } catch (KeystoreInstantiationException kie) {
        log.error(kie.getMessage());
        addActionError(getText("exception.keystoreInstantiation"));
        return ERROR;
    }
    addActionMessage(getText("secureFTPBean.deleteCertificateSuccessful"));
    log.debug("delete() - END");
    return SUCCESS;
}