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.KeystoreCryptoToken.java

@Override
public boolean removeKey(String alias)
        throws CryptoTokenOfflineException, KeyStoreException, SignServerException {
    final KeyStore keyStore = getKeyStore();
    boolean result = CryptoTokenHelper.removeKey(keyStore, alias);
    if (result) {
        OutputStream out = null;/*w w  w .ja v a2s  . com*/
        try {
            if (!TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) {
                out = new FileOutputStream(new File(keystorepath));
            } else {
                // use internal worker data
                out = new ByteArrayOutputStream();
            }
            keyStore.store(out, authenticationCode);

            if (TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) {
                final byte[] data = ((ByteArrayOutputStream) out).toByteArray();

                getWorkerSession().setKeystoreData(new AdminInfo("Internal", null, null), this.workerId, data);
            }

            readFromKeystore(null);
        } catch (NamingException ex) {
            LOG.error("Unable to lookup worker session: " + ex.getMessage(), ex);
            throw new SignServerException("Unable to persist key removal");
        } catch (IOException ex) {
            LOG.error("Unable to persist new keystore after key removal: " + ex.getMessage(), ex);
            throw new SignServerException("Unable to persist key removal");
        } catch (NoSuchAlgorithmException ex) {
            LOG.error("Unable to persist new keystore after key removal: " + ex.getMessage(), ex);
            throw new SignServerException("Unable to persist key removal");
        } catch (CertificateException ex) {
            LOG.error("Unable to persist new keystore after key removal: " + ex.getMessage(), ex);
            throw new SignServerException("Unable to persist key removal");
        } catch (NoSuchProviderException ex) {
            LOG.error("Unable to persist new keystore after key removal: " + ex.getMessage(), ex);
            throw new SignServerException("Unable to persist key removal");
        } catch (UnrecoverableKeyException ex) {
            LOG.error("Unable to persist new keystore after key removal: " + ex.getMessage(), ex);
            throw new SignServerException("Unable to persist key removal");
        } finally {
            IOUtils.closeQuietly(out);
        }
    }
    return result;
}

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

/** Finds or creates the PKCS12 keystore specified by the given path.
 *
 * @param filePath the file path to the keystore, having the .pkcs12 extension
 * @param password the keystore password
 * @return the keystore/*from  ww w.j  a va 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 findOrCreatePKCS12KeyStore(final String filePath, final char[] password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        NoSuchProviderException {
    //Preconditions
    assert filePath != null : "filePath must not be null";
    assert filePath.endsWith(".p12") : "file extension must be .p12";
    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;
    if (isJCEUnlimitedStrengthPolicy()) {
        keyStore = KeyStore.getInstance("pkcs12", BOUNCY_CASTLE_PROVIDER);
    } else {
        keyStore = KeyStore.getInstance("pkcs12");
    }
    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 keystore specified by the given path.
 *
 * @param filePath the file path to the keystore
 * @param password the keystore password
 * @return the keystore//from  w  w w .  j a  v  a  2s. 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 findOrCreateKeyStore(final String filePath, final char[] password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        NoSuchProviderException {
    //Preconditions
    assert filePath != null : "filePath must not be null";
    if (isJCEUnlimitedStrengthPolicy()) {
        assert filePath.endsWith(".uber") : "file extension must be .uber";
    } else {
        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);
    KeyStore keyStore;
    if (isJCEUnlimitedStrengthPolicy()) {
        keyStore = KeyStore.getInstance("UBER", BOUNCY_CASTLE_PROVIDER);
    } else {
        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);
        }
    }

    //Postconditions
    assert !filePath.endsWith(".uber") || keyStore.getType().equals("UBER") : "keyStore type is "
            + keyStore.getType() + ", expected UBER, filePath: " + filePath;

    return keyStore;
}

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

/**
 * Tests that a worker just set up with a key store containing a new
 * key-pair and is activated manually gets status ACTIVE.
 * @throws Exception/*  www  . jav  a  2  s .c om*/
 */
public void testActivateWithNewKeystore() throws Exception {
    LOG.info("testActivateWithNewKeystore");

    final boolean autoActivate = false;

    final int workerId = WORKER_CMS;
    try {
        setCMSSignerPropertiesCombined(workerId, autoActivate);

        // Create a key-pair and certificate in the keystore
        FileOutputStream out = null;
        try {
            KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
            ks.load(null, null);

            // Generate key and issue certificate
            final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
            kpg.initialize(1024);
            final KeyPair keyPair = kpg.generateKeyPair();
            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = getSelfCertificate("CN=TestActivateWithNewKeystore" + ", C=SE",
                    (long) 30 * 24 * 60 * 60 * 365, keyPair);
            ks.setKeyEntry("newkey11", keyPair.getPrivate(), pin.toCharArray(), chain);

            out = new FileOutputStream(keystoreFile);
            ks.store(out, pin.toCharArray());
        } finally {
            IOUtils.closeQuietly(out);
        }

        workerSession.setWorkerProperty(workerId, "DEFAULTKEY", "newkey11");
        workerSession.reloadConfiguration(workerId);

        // Activate first so we can generate a key
        workerSession.activateSigner(workerId, pin);

        List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
        assertTrue("Fatal errors: " + errors, workerSession.getStatus(workerId).getFatalErrors().isEmpty());

    } finally {
        FileUtils.deleteQuietly(keystoreFile);
        removeWorker(workerId);
    }
}

From source file:de.extra.client.plugins.outputplugin.transport.ExtraTransportHttp.java

/**
 * Sets up the Truststore./*from   www .  j av a2 s . c om*/
 * 
 * @param extraConnectData
 * @return
 */
private void setupTruststore(final HttpOutputPluginConnectConfiguration extraConnectData)
        throws ExtraTransportException {

    // Load TrustStoreLocation from properties
    String truststoreLocation = extraConnectData.getSslTruststoreLocation();

    LOG.debug("TruststoreLoc: " + truststoreLocation);

    // If no location specified -> fallback to JRE default
    if (truststoreLocation == null || truststoreLocation.length() == 0) {
        truststoreLocation = System.getProperty("java.home") + File.separatorChar + "lib" + File.separatorChar
                + "security" + File.separatorChar + "cacerts";
    }

    LOG.debug("TruststoreLoc: " + truststoreLocation);

    try {
        // Create keystore instance
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        // KeyStore ks = KeyStore.getInstance("PKCS12");

        // Load keystore values
        FileInputStream fi = new FileInputStream(truststoreLocation);
        ks.load(fi, extraConnectData.getSslTruststorePassword().toCharArray());
        fi.close();

        // Create new certificate based on stored value
        java.security.cert.CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

        X509Certificate cert = (X509Certificate) certFactory
                .generateCertificate(new ByteArrayInputStream(extraConnectData.getSslCertificate().getBytes()));

        // Check if certificate is not already stored -> store and save
        if (extraConnectData.isSslCertificateRefresh() || ks.getCertificateAlias(cert) == null) {

            LOG.info("Zertifikat wird eingetragen");

            ks.store(new FileOutputStream(truststoreLocation),
                    extraConnectData.getSslTruststorePassword().toCharArray());

        }

        // Set truststore location
        System.setProperty("javax.net.ssl.trustStore", truststoreLocation);

    } catch (KeyStoreException e) {
        throw new ExtraTransportException("Fehler bei Zugriff auf Keystore.", e);
    } catch (FileNotFoundException e) {
        throw new ExtraTransportException("Fehler beim Laden des Keystore.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new ExtraTransportException("Fehler beim Laden des Crypto-Algorithmus.", e);
    } catch (CertificateException e) {
        throw new ExtraTransportException("Fehler beim Prfen des Zertifikats.", e);
    } catch (IOException e) {
        throw new ExtraTransportException("Fehler bei I/O-Operation.", e);
    }
}

From source file:org.ejbca.core.model.ca.catoken.CATokenContainerImpl.java

/**
 * Stores keystore bytes and properties of a soft keystore
 * @param authenticationCode//from ww w  . j ava 2s .c o  m
 * @param info
 * @param properties
 * @param keystore
 */
private void storeSoftKeyStore(char[] authenticationCode, SoftCATokenInfo info, Properties properties,
        KeyStore keystore)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    if (log.isTraceEnabled()) {
        log.trace(">storeSoftKeyStore");
    }
    // Store the key store
    java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
    keystore.store(baos, authenticationCode);
    String ksbytes = new String(Base64.encode(baos.toByteArray()));
    if (log.isDebugEnabled()) {
        log.debug("Storing soft keystore of size " + ksbytes.length());
    }
    data.put(KEYSTORE, ksbytes);
    data.put(SIGNKEYSPEC, info.getSignKeySpec());
    data.put(SIGNKEYALGORITHM, info.getSignKeyAlgorithm());
    data.put(SIGNATUREALGORITHM, info.getSignatureAlgorithm());
    data.put(ENCKEYSPEC, info.getEncKeySpec());
    data.put(ENCKEYALGORITHM, info.getEncKeyAlgorithm());
    data.put(ENCRYPTIONALGORITHM, info.getEncryptionAlgorithm());
    // Store any changed properties
    if (properties != null) {
        setProperties(properties);
    }
    if (log.isTraceEnabled()) {
        log.trace("<storeSoftKeyStore");
    }
}

From source file:org.signserver.server.log.SystemLoggingTest.java

private void setupCryptoToken(int tokenId, String tokenName, String pin) throws Exception {
    // Create keystore
    keystoreFile = File.createTempFile("testkeystore", ".p12");
    FileOutputStream out = null;/* w ww. j  a  v  a  2s.com*/
    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", tokenName);
    workerSession.setWorkerProperty(tokenId, "KEYSTORETYPE", "PKCS12");
    workerSession.setWorkerProperty(tokenId, "KEYSTOREPATH", keystoreFile.getAbsolutePath());
    workerSession.setWorkerProperty(tokenId, "KEYSTOREPASSWORD", pin);
    workerSession.reloadConfiguration(tokenId);
}

From source file:org.ejbca.ui.web.pub.CertDistServlet.java

private void handleCaChainCommands(AuthenticationToken administrator, String issuerdn, int caid, String format,
        HttpServletResponse res) throws IOException, NoSuchFieldException {
    try {/*from w ww . j  a v  a 2 s . c  o m*/
        Certificate[] chain = getCertificateChain(administrator, caid, issuerdn);
        // Reverse the chain to get proper ordering for chain file
        // (top-level CA first, requested CA last).
        ArrayUtils.reverse(chain);

        // Construct the filename based on requested CA. Fail-back to
        // name "ca-chain.EXT".
        String filename = RequestHelper.getFileNameFromCertNoEnding(chain[chain.length - 1], "ca") + "-chain."
                + format.toLowerCase();

        byte[] outbytes = new byte[0];
        // Encode and send back
        if ((format == null) || StringUtils.equalsIgnoreCase(format, "pem")) {
            outbytes = CertTools.getPemFromCertificateChain(Arrays.asList(chain));
        } else {
            // Create a JKS truststore with the CA certificates in
            final KeyStore store = KeyStore.getInstance("JKS");
            store.load(null, null);
            for (int i = 0; i < chain.length; i++) {
                String cadn = CertTools.getSubjectDN(chain[i]);
                String alias = CertTools.getPartFromDN(cadn, "CN");
                if (alias == null) {
                    alias = CertTools.getPartFromDN(cadn, "O");
                }
                if (alias == null) {
                    alias = "cacert" + i;
                }
                alias = StringUtils.replaceChars(alias, ' ', '_');
                alias = StringUtils.substring(alias, 0, 15);
                store.setCertificateEntry(alias, chain[i]);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                store.store(out, "changeit".toCharArray());
                out.close();
                outbytes = out.toByteArray();
            }
        }
        // We must remove cache headers for IE
        ServletUtils.removeCacheHeaders(res);
        res.setHeader("Content-disposition",
                "attachment; filename=\"" + StringTools.stripFilename(filename) + "\"");
        res.setContentType("application/octet-stream");
        res.setContentLength(outbytes.length);
        res.getOutputStream().write(outbytes);
        log.debug("Sent CA certificate chain to client, len=" + outbytes.length + ".");
    } catch (CertificateEncodingException e) {
        log.debug("Error getting CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting CA certificate chain.");
    } catch (KeyStoreException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (NoSuchAlgorithmException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (CertificateException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (EJBException e) {
        log.debug("CA does not exist: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND,
                "CA does not exist: " + HTMLTools.htmlescape(e.getMessage()));
    } catch (AuthorizationDeniedException e) {
        log.debug("Authotization denied: ", e);
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Authorization denied: " + HTMLTools.htmlescape(e.getMessage()));
    }
}

From source file:it.cnr.icar.eric.server.security.authentication.CertificateAuthority.java

/** Extension request to sign specified cert and return the signed cert. */
@SuppressWarnings("static-access")
public RegistryResponseHolder signCertificateRequest(UserType user, RegistryRequestType req,
        Map<?, ?> idToRepositoryItemMap) throws RegistryException {

    RegistryResponseHolder respHolder = null;
    RegistryResponseType ebRegistryResponseType = null;
    ServerRequestContext context = null;

    try {//from  w  w  w  .  ja  va 2 s.  c  om
        context = new ServerRequestContext("CertificateAUthority.signCertificateRequest", req);
        context.setUser(user);

        if (idToRepositoryItemMap.keySet().size() == 0) {
            throw new MissingRepositoryItemException(
                    ServerResourceBundle.getInstance().getString("message.KSRepItemNotFound"));
        }

        String id = (String) idToRepositoryItemMap.keySet().iterator().next();

        Object obj = idToRepositoryItemMap.get(id);
        if (!(obj instanceof RepositoryItem)) {
            throw new InvalidContentException();
        }
        RepositoryItem ri = (RepositoryItem) obj; //This is the JKS keystore containing cert to be signed            

        //Read original cert from keystore
        InputStream is = ri.getDataHandler().getInputStream();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray());
        is.close();
        X509Certificate cert = (X509Certificate) keyStore
                .getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ);

        //Sign the cert
        cert = signCertificate(cert);

        //Replace cert with signed cert in keystore
        keyStore.deleteEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ);
        keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP, cert);

        //Add CA root cert (RegistryOPerator's cert) to keystore.
        keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_CACERT_ALIAS, getCACertificate());

        Certificate[] certChain = new Certificate[2];
        certChain[0] = cert;
        certChain[1] = getCACertificate();
        validateChain(certChain);

        File repositoryItemFile = File.createTempFile(".eric-ca-resp", ".jks");
        repositoryItemFile.deleteOnExit();
        FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile);
        keyStore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray());
        fos.flush();
        fos.close();

        DataHandler dh = new DataHandler(new FileDataSource(repositoryItemFile));
        RepositoryItemImpl riNew = new RepositoryItemImpl(id, dh);

        ebRegistryResponseType = bu.rsFac.createRegistryResponseType();
        ebRegistryResponseType.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success);

        HashMap<String, Object> respIdToRepositoryItemMap = new HashMap<String, Object>();
        respIdToRepositoryItemMap.put(id, riNew);

        respHolder = new RegistryResponseHolder(ebRegistryResponseType, respIdToRepositoryItemMap);

    } catch (RegistryException e) {
        context.rollback();
        throw e;
    } catch (Exception e) {
        context.rollback();
        throw new RegistryException(e);
    }

    context.commit();
    return respHolder;
}