List of usage examples for java.security KeyStore store
public final void store(OutputStream stream, char[] password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException
From source file:com.aperigeek.dropvault.web.dao.MongoFileService.java
protected KeyStore getKeyStore(String username, char[] password) { try {/* ww w. j a v a2s . co m*/ File keyStoreFile = new File(secretsFolder, username + ".jks"); KeyStore keyStore = KeyStore.getInstance("JCEKS"); if (keyStoreFile.exists()) { keyStore.load(new FileInputStream(keyStoreFile), password); return keyStore; } else { KeyGenerator gen = KeyGenerator.getInstance("Blowfish"); SecretKey key = gen.generateKey(); keyStore.load(null, password); keyStore.setEntry(username, new SecretKeyEntry(key), new KeyStore.PasswordProtection(password)); keyStore.store(new FileOutputStream(keyStoreFile), password); return keyStore; } } catch (Exception ex) { // TODO: better exception handling Logger.getAnonymousLogger().log(Level.SEVERE, "ERROR", ex); throw new RuntimeException(ex); } }
From source file:com.mhise.util.MHISEUtil.java
/** * Returns a list of the file path containing file with extensions .p12 , .pfx , .p7b * *//*from ww w . j a v a 2s. com*/ public static void movePKCS12(String path, Context ctx) { //Move PFX or p12 store to Mobius store /* try { File certificateFile=new File(path); File _mobiusDirectory = new File(Constants.defaultP12StorePath); if(!_mobiusDirectory.exists()) { _mobiusDirectory.mkdir(); } File newKeystoreFile = new File(Constants.defaultP12StorePath + Constants.defaultP12StoreName); FileInputStream fin= new FileInputStream(certificateFile); FileOutputStream fout= new FileOutputStream(newKeystoreFile); byte buffer[] = new byte[(int) certificateFile.length()]; fin.read(buffer); fout.write(buffer); movedPath = newKeystoreFile.getAbsolutePath(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); //Get saved password SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE); String strPassword = sharedPreferences.getString(Constants.KEY_PKCS12_PASSWORD, null); char[] password = strPassword.toCharArray(); //Load Selected keystore File input = new File(path); FileInputStream fin = new FileInputStream(input); keyStore.load(fin, password); OutputStream fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE); keyStore.store(fos, password); fos.close(); } catch (KeyStoreException e) { // TODO: handle exception Logger.debug("MHISEUtil-->makePKCS12Store", "KeyStoreException: " + e); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Logger.debug("MHISEUtil-->makePKCS12Store", "FileNotFoundException: " + e); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block Logger.debug("MHISEUtil-->makePKCS12Store", "NoSuchAlgorithmException: " + e); e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block Logger.debug("MHISEUtil-->makePKCS12Store", "CertificateException: " + e); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block Logger.debug("MHISEUtil-->makePKCS12Store", "IOException: " + e); e.printStackTrace(); } }
From source file:mitm.common.tools.PfxTool.java
private void mergePfx() throws Exception { if (StringUtils.isEmpty(destFile)) { throw new MissingOptionException(destOption.getOpt() + " is missing."); }// w ww . ja v a2 s . c o m if (StringUtils.isEmpty(destPassword)) { throw new MissingOptionException(destPasswordOption.getOpt() + " is missing."); } KeyStore inStore = loadKeyStore(inFile, true, inPassword); KeyStore destStore = loadKeyStore(destFile, false, destPassword); Enumeration<String> aliases = inStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); String destAlias = retainAliases ? alias : UUID.randomUUID().toString() + "_" + alias; if (inStore.isKeyEntry(alias)) { KeyStore.Entry entry = inStore.getEntry(alias, new KeyStore.PasswordProtection(inPassword.toCharArray())); destStore.setEntry(destAlias, entry, new KeyStore.PasswordProtection(destPassword.toCharArray())); } else { Certificate certificate = inStore.getCertificate(alias); destStore.setCertificateEntry(destAlias, certificate); } } destStore.store(new FileOutputStream(destFile), destPassword.toCharArray()); }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * This method will remove certificate from the trust store which matches the given alias. * * @param alias : The alias which the certificate should be deleted. * @return : ResponseCode based on the execution. * <p>//from w w w . j a v a2 s . c o m * Response Codes * SUCCESS : If the certificate is deleted successfully. * INTERNAL_SERVER_ERROR : If any exception occurred. * CERTIFICATE_NOT_FOUND : If the Alias is not found in the key store. */ public ResponseCode removeCertificateFromTrustStore(String alias) { boolean isExists; //Check for the existence of the certificate in trust store. try { File trustStoreFile = new File(TRUST_STORE); localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); if (trustStore.containsAlias(alias)) { trustStore.deleteEntry(alias); isExists = true; } else { isExists = false; if (log.isDebugEnabled()) { log.debug("Certificate for alias '" + alias + "' not found in the trust store."); } } fileOutputStream = new FileOutputStream(trustStoreFile); trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD); responseCode = isExists ? ResponseCode.SUCCESS : ResponseCode.CERTIFICATE_NOT_FOUND; } catch (IOException e) { log.error("Error in loading the certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (CertificateException e) { log.error("Error loading certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (NoSuchAlgorithmException e) { log.error("Could not find the algorithm to load the certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (KeyStoreException e) { log.error("Error reading certificate contents.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } finally { closeStreams(localTrustStoreStream, fileOutputStream); } return responseCode; }
From source file:org.signserver.server.cryptotokens.KeystoreCryptoTokenTest.java
/** * Test importing a new certificate chain to an existing keystore. * @throws Exception //from ww w. j a v a 2 s . co m */ public void testImportCertificateChain() throws Exception { LOG.info("testImportCertificateChain"); final boolean autoActivate = false; final int workerId = WORKER_CMS; try { setCMSSignerPropertiesCombined(workerId, autoActivate); // Generate key and issue certificate final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC"); kpg.initialize(1024); final KeyPair keyPair = kpg.generateKeyPair(); // Create a key-pair and certificate in the keystore FileOutputStream out = null; try { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null, null); final X509Certificate[] chain = new X509Certificate[1]; chain[0] = getSelfCertificate("CN=Test", (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()); // generate a new certificate final X509Certificate newCert = getSelfCertificate("CN=TestNew", (long) 30 * 24 * 60 * 60 * 365, keyPair); workerSession.importCertificateChain(workerId, Arrays.asList(newCert.getEncoded()), "newkey11", null); final Certificate readCert = workerSession.getSignerCertificate(workerId); assertTrue("Matching certificates", Arrays.equals(newCert.getEncoded(), readCert.getEncoded())); } finally { FileUtils.deleteQuietly(keystoreFile); removeWorker(workerId); } }
From source file:org.tolven.config.model.CredentialManager.java
private void write(KeyStore keyStore, File keyStoreFile, char[] password) { File file = null;//from w w w .j a v a 2 s .c o m FileOutputStream out = null; try { try { keyStoreFile.getParentFile().mkdirs(); out = new FileOutputStream(keyStoreFile); keyStore.store(out, password); } catch (Exception ex) { if (file != null) { file.delete(); } throw new RuntimeException("Could not create keystore file: " + keyStoreFile.getPath(), ex); } finally { if (out != null) out.close(); } } catch (IOException ex) { throw new RuntimeException("Could not store keystore file " + keyStoreFile.getPath(), ex); } }
From source file:org.freebxml.omar.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 * * @param alias// w w w. j av a 2 s . co m * 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) { } } } }
From source file:org.wso2.carbon.core.util.KeyStoreManager.java
/** * Update the key store with the given name using the modified key store object provided. * * @param name key store name/*from w w w .j av a2s . c om*/ * @param keyStore modified key store object * @throws Exception Registry exception or Security Exception */ public void updateKeyStore(String name, KeyStore keyStore) throws Exception { ServerConfigurationService config = this.getServerConfigService(); if (KeyStoreUtil.isPrimaryStore(name)) { String file = new File( config.getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_FILE)) .getAbsolutePath(); FileOutputStream out = null; try { out = new FileOutputStream(file); String password = config .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_PASSWORD); keyStore.store(out, password.toCharArray()); } finally { if (out != null) { out.close(); } } return; } String path = RegistryResources.SecurityManagement.KEY_STORES + "/" + name; org.wso2.carbon.registry.api.Resource resource = registry.get(path); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil(); String encryptedPassword = resource.getProperty(RegistryResources.SecurityManagement.PROP_PASSWORD); String password = new String(cryptoUtil.base64DecodeAndDecrypt(encryptedPassword)); keyStore.store(outputStream, password.toCharArray()); outputStream.flush(); outputStream.close(); resource.setContent(outputStream.toByteArray()); registry.put(path, resource); resource.discard(); updateKeyStoreCache(name, new KeyStoreBean(keyStore, new Date())); }
From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java
public void handlePost(RequestContext context) throws ServletException, IOException { HttpServletRequest request = context.getRequest(); HttpServletResponse response = context.getResponse(); if (!checkConfiguration(response)) return;/*from ww w. j ava 2 s . co m*/ List<?> parameters = extractParameterList(request); String orgName = extractParameter("organisationName", parameters); String orgUrl = extractParameter("organisationUrl", parameters); String email = extractParameter("email", parameters); String entityId = extractParameter("entityId", parameters); final String password = extractParameter("keystorePassword", parameters); byte[] metadata = extractFile("metadata", parameters).get(); FileItem ksData = extractFile("keystore", parameters); byte[] keystore = null; if (ksData != null) { keystore = ksData.get(); } if (!checkNotNull(orgName, orgUrl, email, password, metadata, entityId) || metadata.length == 0 || (keystore == null && !Boolean.valueOf(extractParameter("createkeystore", parameters)))) { Map<String, Object> params = getStandardParameters(request); params.put("error", "All fields must be filled."); params.put("organisationName", orgName); params.put("organisationUrl", orgUrl); params.put("email", email); params.put("keystorePassword", password); params.put("entityId", entityId); log.info("Parameters not correct: " + params); log.info("Metadata: " + new String(metadata)); String res = renderTemplate("configure.vm", params, true); sendResponse(response, res); return; } Credential credential = context.getCredential(); if (keystore != null && keystore.length > 0) { credential = CredentialRepository.createCredential(new ByteArrayInputStream(keystore), password); } else if (Boolean.valueOf(extractParameter("createkeystore", parameters))) { try { BasicX509Credential cred = new BasicX509Credential(); KeyPair kp = dk.itst.oiosaml.security.SecurityHelper .generateKeyPairFromURI("http://www.w3.org/2001/04/xmlenc#rsa-1_5", 1024); cred.setPrivateKey(kp.getPrivate()); cred.setPublicKey(kp.getPublic()); credential = cred; KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); X509Certificate cert = dk.itst.oiosaml.security.SecurityHelper.generateCertificate(credential, getEntityId(request)); cred.setEntityCertificate(cert); ks.setKeyEntry("oiosaml", credential.getPrivateKey(), password.toCharArray(), new Certificate[] { cert }); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ks.store(bos, password.toCharArray()); keystore = bos.toByteArray(); bos.close(); } catch (Exception e) { log.error("Unable to generate credential", e); throw new RuntimeException("Unable to generate credential", e); } } EntityDescriptor descriptor = generateSPDescriptor(getBaseUrl(request), entityId, credential, orgName, orgUrl, email, Boolean.valueOf(extractParameter("enableArtifact", parameters)), Boolean.valueOf(extractParameter("enablePost", parameters)), Boolean.valueOf(extractParameter("enableSoap", parameters)), Boolean.valueOf(extractParameter("enablePostSLO", parameters)), Boolean.valueOf(extractParameter("supportOCESAttributeProfile", parameters))); File zipFile = generateZipFile(request.getContextPath(), password, metadata, keystore, descriptor); byte[] configurationContents = saveConfigurationInSession(request, zipFile); boolean written = writeConfiguration(getHome(servletContext), configurationContents); Map<String, Object> params = new HashMap<String, Object>(); params.put("home", getHome(servletContext)); params.put("written", written); sendResponse(response, renderTemplate("done.vm", params, true)); }
From source file:org.texai.x509.X509Utils.java
/** Initializes the installer keystore on the trusted development system, from where it is copied into the distributed code. */ public static synchronized void initializeInstallerKeyStore() { if (!X509Utils.isTrustedDevelopmentSystem()) { return;//w ww.j a v a 2 s .c o m } String filePath = "data/installer-keystore.uber"; File file = new File(filePath); if (file.exists()) { // do not overwrite it return; } try { LOGGER.info("creating the installer keystores"); // the installer keystore consists of the single client X.509 certificate, which is generated and signed by // the Texai root certificate on the developement system that has the root private key. final KeyPair installerKeyPair = X509Utils.generateRSAKeyPair2048(); final X509Certificate installerX509Certificate = X509Utils.generateX509Certificate( installerKeyPair.getPublic(), X509Utils.getRootPrivateKey(), X509Utils.getRootX509Certificate(), null); // proceed as though the JCE unlimited strength jurisdiction policy files are installed, which they will be on the // trusted development system. LOGGER.info("creating installer-keystore.uber"); assert X509Utils.isJCEUnlimitedStrengthPolicy(); KeyStore installerKeyStore = X509Utils.findOrCreateKeyStore(filePath, INSTALLER_KEYSTORE_PASSWORD); installerKeyStore.setKeyEntry(X509Utils.ENTRY_ALIAS, installerKeyPair.getPrivate(), INSTALLER_KEYSTORE_PASSWORD, new Certificate[] { installerX509Certificate, X509Utils.getRootX509Certificate() }); installerKeyStore.store(new FileOutputStream(filePath), INSTALLER_KEYSTORE_PASSWORD); // then proceed after disabling the JCE unlimited strength jurisdiction policy files indicator X509Utils.setIsJCEUnlimitedStrengthPolicy(false); filePath = "data/installer-keystore.jceks"; LOGGER.info("creating installer-keystore.jceks"); installerKeyStore = X509Utils.findOrCreateKeyStore(filePath, INSTALLER_KEYSTORE_PASSWORD); installerKeyStore.setKeyEntry(X509Utils.ENTRY_ALIAS, installerKeyPair.getPrivate(), INSTALLER_KEYSTORE_PASSWORD, new Certificate[] { installerX509Certificate, X509Utils.getRootX509Certificate() }); installerKeyStore.store(new FileOutputStream(filePath), INSTALLER_KEYSTORE_PASSWORD); // restore the JCE unlimited strength jurisdiction policy files indicator X509Utils.setIsJCEUnlimitedStrengthPolicy(true); } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException | SignatureException | InvalidKeyException | IOException | KeyStoreException | CertificateException ex) { LOGGER.error(StringUtils.getStackTraceAsString(ex)); throw new TexaiException(ex); } //Postconditions assert !isTrustedDevelopmentSystem() || X509Utils.isJCEUnlimitedStrengthPolicy() : "JCE unlimited strength policy must be in effect"; }