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:net.sf.keystore_explorer.crypto.keystore.KeyStoreUtil.java
/** * Copy a KeyStore.//from ww w .ja v a2s . co m * * @param keyStore * KeyStore to copy * @return Copy * @throws CryptoException * Problem encountered copying the KeyStore */ public static KeyStore copy(KeyStore keyStore) throws CryptoException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { char[] emptyPassword = {}; keyStore.store(baos, emptyPassword); KeyStore theCopy = KeyStoreUtil.create(KeyStoreType.resolveJce(keyStore.getType())); theCopy.load(new ByteArrayInputStream(baos.toByteArray()), emptyPassword); return theCopy; } catch (CryptoException ex) { throw new CryptoException(res.getString("NoCopyKeyStore.exception.message"), ex); } catch (GeneralSecurityException ex) { throw new CryptoException(res.getString("NoCopyKeyStore.exception.message"), ex); } catch (IllegalStateException ex) { throw new CryptoException(res.getString("NoCopyKeyStore.exception.message"), ex); } catch (IOException ex) { throw new CryptoException(res.getString("NoCopyKeyStore.exception.message"), ex); } }
From source file:com.eucalyptus.www.X509Download.java
private static byte[] getX509Zip(User u) throws Exception { X509Certificate cloudCert = null; final X509Certificate x509; String userAccessKey = null;/*www. ja va 2 s. co m*/ String userSecretKey = null; KeyPair keyPair = null; try { for (AccessKey k : u.getKeys()) { if (k.isActive()) { userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } } if (userAccessKey == null) { AccessKey k = u.createKey(); userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } keyPair = Certs.generateKeyPair(); x509 = Certs.generateCertificate(keyPair, u.getName()); x509.checkValidity(); u.addCertificate(x509); cloudCert = SystemCredentials.lookup(Eucalyptus.class).getCertificate(); } catch (Exception e) { LOG.fatal(e, e); throw e; } ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(byteOut); ZipArchiveEntry entry = null; String fingerPrint = Certs.getFingerPrint(keyPair.getPublic()); if (fingerPrint != null) { String baseName = X509Download.NAME_SHORT + "-" + u.getName() + "-" + fingerPrint.replaceAll(":", "").toLowerCase().substring(0, 8); zipOut.setComment("To setup the environment run: source /path/to/eucarc"); StringBuilder sb = new StringBuilder(); //TODO:GRZE:FIXME velocity String userNumber = u.getAccount().getAccountNumber(); sb.append("EUCA_KEY_DIR=$(cd $(dirname ${BASH_SOURCE:-$0}); pwd -P)"); final Optional<String> computeUrl = remotePublicify(Compute.class); if (computeUrl.isPresent()) { sb.append(entryFor("EC2_URL", null, computeUrl)); } else { sb.append("\necho WARN: Eucalyptus URL is not configured. >&2"); ServiceBuilder<? extends ServiceConfiguration> builder = ServiceBuilders.lookup(Compute.class); ServiceConfiguration localConfig = builder.newInstance(Internets.localHostAddress(), Internets.localHostAddress(), Internets.localHostAddress(), Eucalyptus.INSTANCE.getPort()); sb.append("\nexport EC2_URL=" + ServiceUris.remotePublicify(localConfig)); } sb.append(entryFor("S3_URL", "An OSG is either not registered or not configured. S3_URL is not set. " + "Please register an OSG and/or set a valid s3 endpoint and download credentials again. " + "Or set S3_URL manually to http://OSG-IP:8773/services/objectstorage", remotePublicify(ObjectStorage.class))); sb.append(entryFor("EUARE_URL", "EUARE URL is not configured.", remotePublicify(Euare.class))); sb.append(entryFor("TOKEN_URL", "TOKEN URL is not configured.", remotePublicify(Tokens.class))); sb.append(entryFor("AWS_AUTO_SCALING_URL", "Auto Scaling service URL is not configured.", remotePublicify(AutoScaling.class))); sb.append(entryFor("AWS_CLOUDFORMATION_URL", null, remotePublicify(CloudFormation.class))); sb.append(entryFor("AWS_CLOUDWATCH_URL", "Cloud Watch service URL is not configured.", remotePublicify(CloudWatch.class))); sb.append(entryFor("AWS_ELB_URL", "Load Balancing service URL is not configured.", remotePublicify(LoadBalancing.class))); sb.append("\nexport EUSTORE_URL=" + StackConfiguration.DEFAULT_EUSTORE_URL); sb.append("\nexport EC2_PRIVATE_KEY=${EUCA_KEY_DIR}/" + baseName + "-pk.pem"); sb.append("\nexport EC2_CERT=${EUCA_KEY_DIR}/" + baseName + "-cert.pem"); sb.append("\nexport EC2_JVM_ARGS=-Djavax.net.ssl.trustStore=${EUCA_KEY_DIR}/jssecacerts"); sb.append("\nexport EUCALYPTUS_CERT=${EUCA_KEY_DIR}/cloud-cert.pem"); sb.append("\nexport EC2_ACCOUNT_NUMBER='" + u.getAccount().getAccountNumber() + "'"); sb.append("\nexport EC2_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport EC2_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport AWS_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_CREDENTIAL_FILE=${EUCA_KEY_DIR}/iamrc"); sb.append("\nexport EC2_USER_ID='" + userNumber + "'"); sb.append( "\nalias ec2-bundle-image=\"ec2-bundle-image --cert ${EC2_CERT} --privatekey ${EC2_PRIVATE_KEY} --user ${EC2_ACCOUNT_NUMBER} --ec2cert ${EUCALYPTUS_CERT}\""); sb.append( "\nalias ec2-upload-bundle=\"ec2-upload-bundle -a ${EC2_ACCESS_KEY} -s ${EC2_SECRET_KEY} --url ${S3_URL}\""); sb.append("\n"); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("eucarc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); sb = new StringBuilder(); sb.append("AWSAccessKeyId=").append(userAccessKey).append('\n'); sb.append("AWSSecretKey=").append(userSecretKey); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("iamrc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry("cloud-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(cloudCert)); zipOut.closeArchiveEntry(); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("jssecacerts")); entry.setUnixMode(0600); KeyStore tempKs = KeyStore.getInstance("jks"); tempKs.load(null); tempKs.setCertificateEntry("eucalyptus", cloudCert); ByteArrayOutputStream bos = new ByteArrayOutputStream(); tempKs.store(bos, "changeit".toCharArray()); zipOut.write(bos.toByteArray()); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-pk.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes("RSA PRIVATE KEY", Crypto.getCertificateProvider().getEncoded(keyPair.getPrivate()))); zipOut.closeArchiveEntry(); /** write the X509 certificate to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(x509)); zipOut.closeArchiveEntry(); } /** close the zip output stream and return the bytes **/ zipOut.close(); return byteOut.toByteArray(); }
From source file:org.jboss.as.test.integration.logging.handlers.SocketHandlerTestCase.java
private static Path createTemporaryKeyStoreFile(final KeyStore keyStore, final String fileName) throws Exception { final Path file = TEMP_DIR.resolve(fileName); try (OutputStream fos = Files.newOutputStream(file)) { keyStore.store(fos, KEYSTORE_CREATION_PASSWORD); }//from w w w. jav a2s. c o m return file; }
From source file:mitm.BouncyCastleSslEngineSource.java
public static Certificate initializeKeyStoreStatic(Authority authority) throws RootCertificateException, GeneralSecurityException, OperatorCreationException, IOException { if (authority.aliasFile(KEY_STORE_FILE_EXTENSION).exists() && authority.aliasFile(".pem").exists()) { return KeyStore.getInstance(KEY_STORE_TYPE).getCertificate(authority.alias()); }/*from ww w. j av a 2 s . c o 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); return cert; }
From source file:org.paxml.util.CryptoUtils.java
private static KeyStore getKeyStore(final File file, final String password) { final String key = file.getAbsolutePath(); KeyStore keyStore; final char[] pwd = password.toCharArray(); if (!file.exists()) { FileOutputStream fos = null; try {// www. j av a 2 s . c o m file.getParentFile().mkdirs(); fos = new FileOutputStream(file); // keystore file not created yet => create it keyStore = KeyStore.getInstance(KEY_STORE_TYPE); keyStore.load(null, null); keyStore.store(fos, pwd); } catch (Exception e) { throw new PaxmlRuntimeException("Cannot create new key store file: " + key, e); } finally { IOUtils.closeQuietly(fos); } } FileInputStream fis = null; try { fis = new FileInputStream(file); keyStore = KeyStore.getInstance(KEY_STORE_TYPE); // keystore file already exists => load it keyStore.load(fis, pwd); } catch (Exception e) { throw new PaxmlRuntimeException("Cannot read from key store file: " + key, e); } finally { IOUtils.closeQuietly(fis); } return keyStore; }
From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java
/** * Creates a custom SSL context where clients will trust own CA and self-signed certificates and associates a HTTP client to the context. * @return a HTTP client that will trust own CA and self-signed certificates. * @throws Exception if an error occurs. *///w w w . j a v a 2 s. c o m private static final CloseableHttpClient createHttpClient(final File trustStoreDir, final char[] password, final String url) { CloseableHttpClient httpClient = null; try { final File trustStoreFile = new File(trustStoreDir, "trusted.keystore"); final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // create a new, empty trust store if (!trustStoreFile.exists()) { trustStoreDir.mkdirs(); trustStoreFile.createNewFile(); trustStore.load(null, password); } // import certificate to trust store importCertificate(url, trustStore); // save trust store to disk try (final FileOutputStream outstream = new FileOutputStream(trustStoreFile)) { trustStore.store(outstream, password); } // trust own CA and all self-signed certificates final SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); // allow trusted protocols only final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "SSLv2Hello", "TLSv1", "TLSv1.1", "TLSv1.2" }, null, new DefaultHostnameVerifier()); httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (Exception e) { LOGGER.error("Failed to create HTTP client", e); } return httpClient; }
From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java
final public static KeyStore genNewKeyStore(final File keystorefile, final char[] keystorepass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { final KeyStore ks = KeyStore.getInstance(STORETYPE); ks.load((InputStream) null, keystorepass); final FileOutputStream out = new FileOutputStream(keystorefile); try {/*from w ww . j ava 2s . c o m*/ ks.store(out, keystorepass); } finally { out.close(); } return ks; }
From source file:com.piusvelte.taplock.server.TapLockServer.java
protected static void setPassphrase(String passphrase) { Properties prop = new Properties(); try {// ww w . j a va 2 s.c om prop.load(new FileInputStream(sProperties)); prop.setProperty(sPassphraseKey, passphrase); prop.store(new FileOutputStream(sProperties), null); } catch (FileNotFoundException e) { writeLog("prop load: " + e.getMessage()); } catch (IOException e) { writeLog("prop load: " + e.getMessage()); } if (OS == OS_WIN) { KeyStore ks = getKeyStore(); if (ks != null) { SecretKey sk = getSecretKey(ks); if (ks != null) { try { ks.setKeyEntry(TAP_LOCK, sk, sPassphrase.toCharArray(), null); ks.store(new FileOutputStream(sKeystore), sPassphrase.toCharArray()); } catch (KeyStoreException e) { writeLog("change key password: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { writeLog("change key password: " + e.getMessage()); } catch (CertificateException e) { writeLog("change key password: " + e.getMessage()); } catch (FileNotFoundException e) { writeLog("change key password: " + e.getMessage()); } catch (IOException e) { writeLog("change key password: " + e.getMessage()); } } } } sPassphrase = passphrase; }
From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java
@SuppressWarnings("static-access") private static Certificate[] getCertificateSignedByRegistry(LifeCycleManager lcm, X509Certificate inCert) throws JAXRException { Certificate[] certChain = new Certificate[2]; try {/*ww w. j av a 2 s. c o m*/ // Save cert in a temporary keystore file which is sent as // repository item to server so it can be signed KeyStore tmpKeystore = KeyStore.getInstance("JKS"); tmpKeystore.load(null, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray()); tmpKeystore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ, inCert); File repositoryItemFile = File.createTempFile(".eric-ca-req", ".jks"); repositoryItemFile.deleteOnExit(); FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile); tmpKeystore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray()); fos.flush(); fos.close(); // Now have server sign the cert using extensionRequest javax.activation.DataHandler repositoryItem = new DataHandler(new FileDataSource(repositoryItemFile)); String id = it.cnr.icar.eric.common.Utility.getInstance().createId(); HashMap<String, Object> idToRepositoryItemsMap = new HashMap<String, Object>(); idToRepositoryItemsMap.put(id, repositoryItem); HashMap<String, String> slotsMap = new HashMap<String, String>(); slotsMap.put(BindingUtility.FREEBXML_REGISTRY_PROTOCOL_SIGNCERT, "true"); RegistryRequestType req = bu.rsFac.createRegistryRequestType(); bu.addSlotsToRequest(req, slotsMap); RegistryResponseHolder respHolder = ((LifeCycleManagerImpl) lcm).extensionRequest(req, idToRepositoryItemsMap); DataHandler responseRepositoryItem = (DataHandler) respHolder.getAttachmentsMap().get(id); InputStream is = responseRepositoryItem.getInputStream(); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray()); is.close(); certChain[0] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP); if (certChain[0] == null) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindUserCert")); } certChain[1] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_CACERT_ALIAS); if (certChain[1] == null) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindCARootCert")); } } catch (Exception e) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertSignFailed"), e); } return certChain; }
From source file:test.integ.be.fedict.trust.util.TestUtils.java
/** * Persist the given private key and corresponding certificate to a keystore * file.//from w w w .j a v a 2s.co m * * @param pkcs12keyStore * The file of the keystore to write the key material to. * @param keyStoreType * The type of the key store format to use. * @param privateKey * The private key to persist. * @param certificate * The X509 certificate corresponding with the private key. * @param keyStorePassword * The keystore password. * @param keyEntryPassword * The keyentry password. */ public static KeyStore persistInKeyStore(File pkcs12keyStore, String keyStoreType, PrivateKey privateKey, Certificate certificate, String keyStorePassword, String keyEntryPassword, String alias) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, keyStorePassword.toCharArray()); keyStore.setKeyEntry(alias, privateKey, keyEntryPassword.toCharArray(), new Certificate[] { certificate }); FileOutputStream keyStoreOut; keyStoreOut = new FileOutputStream(pkcs12keyStore); keyStore.store(keyStoreOut, keyStorePassword.toCharArray()); keyStoreOut.close(); return keyStore; }