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.candlepin.client.DefaultCandlepinClientFacade.java

public void generatePKCS12Certificates(String password) {
    try {/*from   w  ww.  ja  va  2  s  .c om*/
        List<EntitlementCertificate> certs = getCurrentEntitlementCertificates();
        for (EntitlementCertificate cert : certs) {
            KeyStore store = PKCS12Util.createPKCS12Keystore(cert.getX509Certificate(), cert.getPrivateKey(),
                    null);
            File p12File = new File(
                    config.getEntitlementDirPath() + File.separator + cert.getSerial() + ".p12");
            store.store(new FileOutputStream(p12File), password.toCharArray());
        }
    } catch (Exception e) {
        throw new ClientException(e);
    }
}

From source file:com.trsst.Command.java

public static final void writeKeyPairToFile(KeyPair keyPair, X509Certificate cert, String alias, File file,
        char[] pwd) {
    FileInputStream input = null;
    FileOutputStream output = null;
    try {//from w  w  w .  j a v  a  2s .co  m
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        if (file.exists()) {
            input = new FileInputStream(file);
            keyStore.load(new FileInputStream(file), pwd);
            input.close();
        } else {
            keyStore.load(null); // weird but required
        }

        // save my private key
        keyStore.setKeyEntry(alias, keyPair.getPrivate(), pwd, new X509Certificate[] { cert });

        // store away the keystore
        output = new java.io.FileOutputStream(file);
        keyStore.store(output, pwd);
        output.flush();
    } catch (Exception e) {
        log.error("Error while storing key: " + e.getMessage(), e);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                // ignore while closing
                log.trace("Error while closing: " + e.getMessage(), e);
            }
        }
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                // ignore while closing
                log.trace("Error while closing: " + e.getMessage(), e);
            }
        }
    }
}

From source file:com.piusvelte.taplock.server.TapLockServer.java

protected static String encryptString(String decStr) {
    String encStr = null;/*from   ww  w  .  j ava 2  s. c  o  m*/
    KeyStore ks = getKeyStore();
    if (ks != null) {
        SecretKey sk = getSecretKey(ks);
        if (sk == null) {
            // create key
            KeyGenerator kgen = null;
            try {
                kgen = KeyGenerator.getInstance("AES");
            } catch (NoSuchAlgorithmException e) {
                writeLog("encryptString: " + e.getMessage());
            }
            if (kgen != null) {
                int keyLength;
                try {
                    keyLength = Cipher.getMaxAllowedKeyLength("AES");
                } catch (NoSuchAlgorithmException e) {
                    keyLength = 128;
                    writeLog("encryptString: " + e.getMessage());
                }
                kgen.init(keyLength);
                sk = kgen.generateKey();
                // create a keystore
                try {
                    ks.load(null, sPassphrase.toCharArray());
                    ks.setKeyEntry(TAP_LOCK, sk, sPassphrase.toCharArray(), null);
                    ks.store(new FileOutputStream(sKeystore), sPassphrase.toCharArray());
                } catch (NoSuchAlgorithmException e) {
                    writeLog("encryptString: " + e.getMessage());
                } catch (CertificateException e) {
                    writeLog("encryptString: " + e.getMessage());
                } catch (IOException e) {
                    writeLog("encryptString: " + e.getMessage());
                } catch (KeyStoreException e) {
                    writeLog("encryptString: " + e.getMessage());
                }
            }
        }
        if ((sk != null) && (decStr != null)) {
            Cipher cipher;
            try {
                cipher = Cipher.getInstance("AES");
                cipher.init(Cipher.ENCRYPT_MODE, sk);
                return new String(Base64.encodeBase64(cipher.doFinal(decStr.getBytes("UTF-8"))));
            } catch (NoSuchAlgorithmException e) {
                writeLog("encryptString: " + e.getMessage());
            } catch (NoSuchPaddingException e) {
                writeLog("encryptString: " + e.getMessage());
            } catch (InvalidKeyException e) {
                writeLog("encryptString: " + e.getMessage());
            } catch (IllegalBlockSizeException e) {
                writeLog("encryptString: " + e.getMessage());
            } catch (BadPaddingException e) {
                writeLog("encryptString: " + e.getMessage());
            } catch (UnsupportedEncodingException e) {
                writeLog("encryptString: " + e.getMessage());
            }
        }
    }
    return encStr;
}

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

public boolean createKeyStoreImportCert(final String keyStoreName, final String keyStorePwd,
        final String certFile, final String alias) {
    KeyStore trustKeyStore;
    try {//w w  w. j  a va2 s . co m
        trustKeyStore = KeyStore.getInstance("JKS");
        trustKeyStore.load(null, keyStorePwd.toCharArray());
        if (KeyStoreConstant.checkKeyStoreFile(certFile)) {
            final String certificate = KeyStoreConstant.readFile(certFile);
            final X509Certificate newCert = getCertificate(certificate);
            trustKeyStore.setCertificateEntry(alias, newCert);
        }
        trustKeyStore.store(new FileOutputStream(workingDir + keyStoreName), keyStorePwd.toCharArray());
        LOG.info("{} is created", keyStoreName);
        return true;
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
        LOG.error("Failed to create keystore {}", keyStoreName, e);
        return false;
    }
}

From source file:mitm.djigzo.web.pages.admin.SSLCertificateManager.java

public void onSuccess() {
    Check.notNull(password, "password");

    try {/*from  w  ww .  j  a v  a  2 s  . c o m*/
        KeyStore keyStore = getKeyStore();

        File absoluteSslFile = sslFile.isAbsolute() ? sslFile : new File(djigzoHome, sslFile.getPath());

        /*
         * Write the KeyStore to a PFX file with the password used by the Servlet engine
         */
        FileOutputStream fos = new FileOutputStream(absoluteSslFile);

        try {
            keyStore.store(fos, sslPassword.toCharArray());

            fos.flush();

            successfullyInstalled = true;
            restartRequired = true;
        } finally {
            IOUtils.closeQuietly(fos);
        }
    } catch (Exception e) {
        logger.error("Error uploading SSL file.", e);

        uploadError = true;

        uploadErrorMessage = e.getMessage();
    }
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java

private void storeCertificateToStore(String alias, Certificate certificate) {
    KeyStore keyStore;
    try {//from w  ww .  j a  v a 2s. c  o  m
        keyStore = KeyStore.getInstance(AgentConstants.DEVICE_KEYSTORE_TYPE);
        keyStore.setCertificateEntry(alias, certificate);
        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 Certificate received from the SCEP "
                + "Enrollment.");
        log.error(AgentConstants.LOG_APPENDER + e);
        log.warn(AgentConstants.LOG_APPENDER + "SCEP Certificate was not stored in the keystore; "
                + "Hence the device will be re-enrolled during next restart.");
    }
}

From source file:mitm.BouncyCastleSslEngineSource.java

private void initializeKeyStore()
        throws RootCertificateException, GeneralSecurityException, OperatorCreationException, IOException {
    if (authority.aliasFile(KEY_STORE_FILE_EXTENSION).exists() && authority.aliasFile(".pem").exists()) {
        return;//from   w  w w  .j  a  va  2s . co  m
    }
    MillisecondsDuration duration = new MillisecondsDuration();
    KeyStore keystore = CertificateHelper.createRootCertificate(authority, KEY_STORE_TYPE);
    LOG.info("Created root certificate authority key store in {}ms", duration);

    OutputStream os = null;
    try {
        os = new FileOutputStream(authority.aliasFile(KEY_STORE_FILE_EXTENSION));
        keystore.store(os, authority.password());
    } finally {
        IOUtils.closeQuietly(os);
    }

    Certificate cert = keystore.getCertificate(authority.alias());
    exportPem(authority.aliasFile(".pem"), cert);
}

From source file:org.guanxi.sp.engine.security.GuardVerifier.java

/**
 * Blocks Guard access to a service until the Guard can be verified.
 *
 * @param request Standard HttpServletRequest
 * @param response Standard HttpServletResponse
 * @param object handler/* w  w  w. ja v  a2s .  c o m*/
 * @return true if the caller is authorised to use the service
 * @throws Exception if an error occurs
 */
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
        throws Exception {
    String guardID = request.getParameter(Guanxi.WAYF_PARAM_GUARD_ID);
    String sessionID = request.getParameter(Guanxi.WAYF_PARAM_SESSION_ID);

    if ((guardID == null) || (sessionID == null)) {
        logger.error("Cant' verify Guard due to missing parameter");
        request.setAttribute("error", messages.getMessage("engine.error.missing.guard.verification.parameter",
                null, request.getLocale()));
        request.setAttribute("message", messages.getMessage("engine.error.missing.guard.verification.parameter",
                null, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    EntityDescriptorType guardEntityDescriptor = (EntityDescriptorType) servletContext.getAttribute(guardID);
    if (guardEntityDescriptor == null) {
        logger.error("Guard '" + guardID + "' not found in metadata repository");
        request.setAttribute("error",
                messages.getMessage("engine.error.no.guard.metadata", null, request.getLocale()));
        request.setAttribute("message",
                messages.getMessage("engine.error.no.guard.metadata", null, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    Config config = (Config) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_ENGINE_CONFIG);
    if (config == null) {
        logger.error("Guard '" + guardID + "' wants to talk but Engine hasn't finished initialisation");
        request.setAttribute("error",
                messages.getMessage("engine.error.not.initialised", null, request.getLocale()));
        request.setAttribute("message",
                messages.getMessage("engine.error.not.initialised", null, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    // Load the GuanxiGuardService node from the metadata
    GuardRoleDescriptorExtensions guardNativeMetadata = Util.getGuardNativeMetadata(guardEntityDescriptor);

    // Build the REST URL to verify the Guard's session
    String queryString = guardNativeMetadata.getVerifierURL() + "?" + Guanxi.SESSION_VERIFIER_PARAM_SESSION_ID
            + "=" + sessionID;

    // If we haven't already checked the Guard for secure comms, do it now
    if (servletContext.getAttribute(guardID + "SECURE_CHECK_DONE_SP") == null) {
        // Load up the Guard's native metadata...
        GuardRoleDescriptorExtensions guardExt = Util.getGuardNativeMetadata(guardEntityDescriptor);

        // ...and see if it's using HTTPS
        try {
            if (Util.isGuardSecure(guardExt)) {
                logger.info("Probing for Guard certificate for : " + guardID);

                /* If the Guard is using HTTPS then we'll need to connect to it, extract it's
                 * certificate and add it to our truststore. To do that, we'll need to use our
                 * own keystore to let the Guard authenticate us.
                 */
                EntityConnection guardConnection = new EntityConnection(queryString,
                        config.getCertificateAlias(), // alias of cert
                        config.getKeystore(), config.getKeystorePassword(), config.getTrustStore(),
                        config.getTrustStorePassword(), EntityConnection.PROBING_ON);
                X509Certificate guardX509 = guardConnection.getServerCertificate();

                // We've got the Guard's X509 so add it to our truststore...
                KeyStore engineTrustStore = KeyStore.getInstance("jks");
                engineTrustStore.load(new FileInputStream(config.getTrustStore()),
                        config.getTrustStorePassword().toCharArray());
                // ...under it's Subject DN as an alias...
                engineTrustStore.setCertificateEntry(guardID, guardX509);
                // ...and rewrite the trust store
                engineTrustStore.store(new FileOutputStream(config.getTrustStore()),
                        config.getTrustStorePassword().toCharArray());

                // Mark Guard as having been checked for secure comms
                servletContext.setAttribute(guardID + "SECURE_CHECK_DONE_SP", "SECURE");

                logger.info("Added : " + guardID + " to truststore");
            } else {
                // Mark Guard as having been checked for secure comms
                servletContext.setAttribute(guardID + "SECURE_CHECK_DONE_SP", "NOT_SECURE");
            }
        } catch (Exception e) {
            logger.error("Failed to probe Guard : " + guardID + " for cert : ", e);
            request.setAttribute("error",
                    messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale()));
            request.setAttribute("message",
                    messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale()));
            request.getRequestDispatcher(errorPage).forward(request, response);
            return false;
        }
    }

    // Verify that the Guard actually sent the request
    String verificationResult = null;
    try {
        EntityConnection verifierService = new EntityConnection(queryString, config.getCertificateAlias(), // alias of cert
                config.getKeystore(), config.getKeystorePassword(), config.getTrustStore(),
                config.getTrustStorePassword(), EntityConnection.PROBING_OFF);
        verifierService.setDoOutput(true);
        verifierService.connect();
        verificationResult = verifierService.getContentAsString();
    } catch (GuanxiException ge) {
        logger.error("Guard '" + guardID + "' error during verification : ", ge);
        request.setAttribute("error",
                messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale()));
        request.setAttribute("message",
                messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    // Did the Guard verify the session?
    if (!verificationResult.equals(Guanxi.SESSION_VERIFIER_RETURN_VERIFIED)) {
        logger.error("Guard '" + guardID + "' error during verification : " + verificationResult);
        request.setAttribute("error",
                messages.getMessage("engine.error.guard.failed.verification", null, request.getLocale()));
        request.setAttribute("message",
                messages.getMessage("engine.error.guard.failed.verification", null, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    /* Convert the Guard's session ID to an Engine session ID and store the Guard's GuanxiGuardService
     * node under it.
     */
    servletContext.setAttribute(sessionID.replaceAll("GUARD", "ENGINE"), guardEntityDescriptor);

    return true;
}

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

/**
 * //from   w w w .  j  av a 2  s.c o  m
 * @return
 * @throws Exception
 */
public String delete() throws Exception {
    log.debug("delete() - START");
    String secureXDSNAVKeystoreLocation = CaCISUtil
            .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_TRUSTSTORE_LOCATION);
    try {
        CaCISUtil caCISUtil = new CaCISUtil();
        KeyStore keystore = caCISUtil.getKeystore(secureXDSNAVKeystoreLocation,
                CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, CaCISUtil.getProperty(
                        CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_TRUSTSTORE_PASSWORD));
        caCISUtil.releaseKeystore();
        // Delete the certificate
        keystore.deleteEntry(secureXDSNAVBean.getCertificateAlias());

        // Save the new keystore contents
        FileOutputStream out = new FileOutputStream(new File(secureXDSNAVKeystoreLocation));
        keystore.store(out,
                CaCISUtil
                        .getProperty(
                                CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_TRUSTSTORE_PASSWORD)
                        .toCharArray());
        out.close();

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

From source file:test.unit.be.fedict.eid.applet.service.AppletServiceServletTest.java

private void persistKey(File pkcs12keyStore, PrivateKey privateKey, X509Certificate certificate,
        char[] keyStorePassword, char[] keyEntryPassword) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, NoSuchProviderException {
    KeyStore keyStore = KeyStore.getInstance("pkcs12", BouncyCastleProvider.PROVIDER_NAME);
    keyStore.load(null, keyStorePassword);
    LOG.debug("keystore security provider: " + keyStore.getProvider().getName());
    keyStore.setKeyEntry("default", privateKey, keyEntryPassword, new Certificate[] { certificate });
    FileOutputStream keyStoreOut = new FileOutputStream(pkcs12keyStore);
    keyStore.store(keyStoreOut, keyStorePassword);
    keyStoreOut.close();//from  ww w .j a v  a  2s.c  om
}