List of usage examples for java.security KeyStore setEntry
public final void setEntry(String alias, Entry entry, ProtectionParameter protParam) throws KeyStoreException
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 . j a va 2 s . co 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:mitm.djigzo.web.pages.certificate.CertificateImportKey.java
private void importPfx() throws KeyStoreException, NoSuchProviderException, SecurityFactoryFactoryException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableEntryException, WebServiceCheckedException {//w w w . j a v a 2 s .c o m /* * To prevent timeouts on the SOAP connection we should upload the PFX file in batches if the PFX file * contains a large number of entries. The PFX file should therefore be opened. */ KeyStore allKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); if (password == null) { password = ""; } allKeys.load(file.getStream(), password.toCharArray()); KeyAndCertificateWorkflow.MissingKey missingKey = ignoreMissingKey ? KeyAndCertificateWorkflow.MissingKey.SKIP_CERTIFICATE : KeyAndCertificateWorkflow.MissingKey.ADD_CERTIFICATE; int imported = 0; KeyStore batchKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); batchKeys.load(null, password.toCharArray()); Enumeration<String> aliases = allKeys.aliases(); KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(password.toCharArray()); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (allKeys.isKeyEntry(alias)) { KeyStore.Entry entry = allKeys.getEntry(alias, passwordProtection); batchKeys.setEntry(alias, entry, passwordProtection); } else { Certificate certificate = allKeys.getCertificate(alias); batchKeys.setCertificateEntry(alias, certificate); } if (batchKeys.size() >= maxBatchSize) { imported += uploadKeyStore(batchKeys, missingKey, password); batchKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); batchKeys.load(null, password.toCharArray()); } } /* * Check if there are still some entries left to add (happens when the number * of entries is not a multiple of maxBatchSize) */ if (batchKeys.size() > 0) { imported += uploadKeyStore(batchKeys, missingKey, password); } this.importCount = imported; }
From source file:com.aperigeek.dropvault.web.dao.MongoFileService.java
protected KeyStore getKeyStore(String username, char[] password) { try {//from w w w . ja va2 s .c om 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:org.opcfoundation.ua.transport.https.HttpsSettings.java
/** * Set keypairs to a https application. This replaces previous keyManager. * Additional CA certifications can be attached. * /* w ww . ja v a2s . c o m*/ * @param keypairs * @param caCerts * @throws KeyStoreException * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException */ public void setKeyPairs(KeyPair[] keypairs, Cert... caCerts) { try { KeyStore keystore = KeyStore.getInstance("jks"); String password = ""; PasswordProtection prot = new PasswordProtection(password.toCharArray()); keystore.load(null); for (int i = 0; i < keypairs.length; i++) { Certificate[] certs = new Certificate[1 + caCerts.length]; certs[0] = keypairs[i].certificate.certificate; for (int j = 0; j < caCerts.length; j++) { certs[j + 1] = caCerts[j].certificate; } PrivateKeyEntry entry = new PrivateKeyEntry(keypairs[i].privateKey.privateKey, certs); keystore.setEntry("my-key-pair-entry-" + (i + 1), entry, prot); } int count = caCerts.length; for (int i = 0; i < count; i++) { String id = "cacert-" + (i + 1); keystore.setEntry(id, new TrustedCertificateEntry(caCerts[i].certificate), null); } setKeyStore(keystore, ""); } catch (KeyStoreException e) { // Unexpected throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { // Unexpected throw new RuntimeException(e); } catch (CertificateException e) { // Unexpected throw new RuntimeException(e); } catch (IOException e) { // Unexpected throw new RuntimeException(e); } catch (ServiceResultException e) { // Unexpected throw new RuntimeException(e); } }
From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java
@Override protected final void addSecretKey(final KeyStore kstore, final String alias, final String password) throws KeyStoreException { final SecretKeyEntry secretKeyEntry; // Secret key entry final PasswordProtection keyPassword; // Secret key password protection final SecretKey secretKey; // Secret key password final byte[] key; // Secret key as array key = getPasswordArray(password);/* w w w . j a va 2s. com*/ secretKey = new SecretKeySpec(key, getSecretKeyAlgorithm()); LOGGER.debug("Created secret key {} with format {}", Arrays.asList(secretKey.getEncoded()), secretKey.getFormat()); secretKeyEntry = new SecretKeyEntry(secretKey); keyPassword = new PasswordProtection(password.toCharArray()); kstore.setEntry(alias, secretKeyEntry, keyPassword); LOGGER.debug("Added secret key with alias {} and password {}", alias, password); }
From source file:com.wwpass.connection.WWPassConnection.java
public WWPassConnection(X509Certificate cert, PKCS8EncodedKeySpec key, int timeoutSec, String spfeAddr) throws IOException, GeneralSecurityException { timeoutMs = timeoutSec * 1000;/* w w w . ja v a 2s. co m*/ SpfeURL = "https://" + spfeAddr + "/"; // Setting up client certificate and key X509Certificate[] chain = { cert }; KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey privKey = kf.generatePrivate(key); KeyStore.PrivateKeyEntry pke = new KeyStore.PrivateKeyEntry(privKey, chain); //This adds no security but Java requires to password-protect the key byte[] password_bytes = new byte[16]; (new java.security.SecureRandom()).nextBytes(password_bytes); // String password = (new BASE64Encoder()).encode(password_bytes); String password = (new Base64()).encodeToString(password_bytes); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null); keyStore.setEntry("WWPass client key", pke, new KeyStore.PasswordProtection(password.toCharArray())); keyManagerFactory.init(keyStore, password.toCharArray()); SPFEContext = SSLContext.getInstance("TLS"); // Making rootCA certificate InputStream is = null; CertificateFactory cf; X509Certificate rootCA = null; try { is = new ByteArrayInputStream(WWPassCA_DER); cf = CertificateFactory.getInstance("X.509"); rootCA = (X509Certificate) cf.generateCertificate(is); } finally { if (is != null) { is.close(); } } //Creating TrustManager for this CA TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null); ks.setCertificateEntry("WWPass Root CA", rootCA); trustManagerFactory.init(ks); SPFEContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new java.security.SecureRandom()); }
From source file:com.googlecode.onevre.utils.ServerClassLoader.java
private boolean verifyCertificate(X509Certificate cert) { try {// www. j a va 2 s . c o m String keypass = ""; String keystorename = System.getProperty("deployment.user.security.trusted.certs"); if (keystorename == null) { throw new IOException("No trusted certs keystore"); } KeyStore keystore = KeyStore.getInstance("JKS", "SUN"); File file = new File(keystorename); if (!file.exists()) { keystore.load(null, keypass.toCharArray()); } else { keystore.load(new FileInputStream(keystorename), keypass.toCharArray()); } boolean isInStore = false; Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements() && !isInStore) { String alias = aliases.nextElement(); Certificate certificate = keystore.getCertificate(alias); if (certificate != null) { if (certificate.equals(cert)) { isInStore = true; } } } if (!isInStore) { int result = JOptionPane.showConfirmDialog(null, "Do you want to trust the bridge implementation " + "signed by\n" + cert.getSubjectX500Principal().getName(), "Trust source?", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { keystore.setEntry("deploymentusercert-" + System.currentTimeMillis(), new KeyStore.TrustedCertificateEntry(cert), null); FileOutputStream output = new FileOutputStream(keystorename); keystore.store(output, keypass.toCharArray()); output.close(); return true; } return false; } return true; } catch (Throwable t) { t.printStackTrace(); } return false; }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
/** * Instantiates the encryptor and digester using the configuration properties. If the properties * are not found, reasonable defaults are used. * /*from w w w . j a v a 2 s . com*/ * @param provider * The provider to use (ex. BC) * @param keyStore * The keystore from which to load the secret encryption key * @param keyPassword * The secret key password * @throws Exception */ private void configureEncryption(Provider provider, KeyStore keyStore, char[] keyPassword) throws Exception { SecretKey secretKey = null; if (!keyStore.containsAlias(SECRET_KEY_ALIAS)) { logger.debug("encryption key not found, generating new one"); KeyGenerator keyGenerator = KeyGenerator.getInstance(encryptionConfig.getEncryptionAlgorithm(), provider); keyGenerator.init(encryptionConfig.getEncryptionKeyLength()); secretKey = keyGenerator.generateKey(); KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(secretKey); keyStore.setEntry(SECRET_KEY_ALIAS, entry, new KeyStore.PasswordProtection(keyPassword)); } else { logger.debug("found encryption key in keystore"); secretKey = (SecretKey) keyStore.getKey(SECRET_KEY_ALIAS, keyPassword); } /* * Now that we have a secret key, store it in the encryption settings so that we can use it * to encryption things client side. */ encryptionConfig.setSecretKey(secretKey.getEncoded()); encryptor = new KeyEncryptor(); encryptor.setProvider(provider); encryptor.setKey(secretKey); encryptor.setFormat(Output.BASE64); digester = new Digester(); digester.setProvider(provider); digester.setAlgorithm(encryptionConfig.getDigestAlgorithm()); digester.setFormat(Output.BASE64); }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
public void migrateKeystore() { PropertiesConfiguration properties = new PropertiesConfiguration(); properties.setDelimiterParsingDisabled(true); try {//from w w w.j a va2s .c om if (getProperty(PROPERTIES_CORE, "encryption.key") != null) { // load the keystore path and passwords properties.load(ResourceUtil.getResourceStream(this.getClass(), "mirth.properties")); File keyStoreFile = new File(properties.getString("keystore.path")); char[] keyStorePassword = properties.getString("keystore.storepass").toCharArray(); char[] keyPassword = properties.getString("keystore.keypass").toCharArray(); // delete the old JKS keystore keyStoreFile.delete(); // create and load a new one as type JCEKS KeyStore keyStore = KeyStore.getInstance("JCEKS"); keyStore.load(null, keyStorePassword); // deserialize the XML secret key to an Object ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance(); String xml = getProperty(PROPERTIES_CORE, "encryption.key"); /* * This is a fix to account for an error that occurred when testing migration from * version 1.8.2 to 3.0.0. The key was serialized as an instance of * com.sun.crypto.provider.DESedeKey, but fails to correctly deserialize as an * instance of java.security.KeyRep. The fix below extracts the "<default>" node * from the serialized xml and uses that to deserialize to java.security.KeyRep. * (MIRTH-2552) */ Document document = new DocumentSerializer().fromXML(xml); DonkeyElement root = new DonkeyElement(document.getDocumentElement()); DonkeyElement keyRep = root.getChildElement("java.security.KeyRep"); if (keyRep != null) { DonkeyElement defaultElement = keyRep.getChildElement("default"); if (defaultElement != null) { defaultElement.setNodeName("java.security.KeyRep"); xml = defaultElement.toXml(); } } SecretKey secretKey = serializer.deserialize(xml, SecretKey.class); // add the secret key entry to the new keystore KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(secretKey); keyStore.setEntry(SECRET_KEY_ALIAS, entry, new KeyStore.PasswordProtection(keyPassword)); // save the keystore to the filesystem OutputStream keyStoreOuputStream = new FileOutputStream(keyStoreFile); try { keyStore.store(keyStoreOuputStream, keyStorePassword); } finally { IOUtils.closeQuietly(keyStoreOuputStream); } // remove the property from CONFIGURATION removeProperty(PROPERTIES_CORE, "encryption.key"); // reinitialize the security settings initializeSecuritySettings(); } } catch (Exception e) { logger.error("Error migrating encryption key from database to keystore.", e); } }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Change the Keystore and the Truststore's master password to the one * provided. The Keystore and Truststore both use the same password. *///from ww w. j a va 2 s . c o m @Override public void changeMasterPassword(String newMasterPassword) throws CMException { /* * Need to make sure we are initialized before we do anything else, as * the Credential Manager can be created but not initialized. */ initialize(); String oldMasterPassword = masterPassword; KeyStore oldKeystore = keystore; KeyStore oldTruststore = truststore; try { synchronized (keystore) { // Create a new keystore and copy all items from the current // one, encrypting them with the new password KeyStore newKeystore = null; try { // Try to create Taverna's Keystore as Bouncy Castle // UBER-type keystore. newKeystore = KeyStore.getInstance("UBER", "BC"); } catch (Exception ex) { // The requested keystore type is not available from // security providers. String exMessage = "Failed to instantiate a new Bouncy Castle Keystore when changing master password."; throw new CMException(exMessage, ex); } try { // Initialize a new empty keystore newKeystore.load(null, null); } catch (Exception ex) { String exMessage = "Failed to create a new empty Keystore to copy over the entries from the current one."; throw new CMException(exMessage, ex); } Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (REALLY_DISABLED) { if (alias.startsWith("password#")) { // a password entry SecretKeySpec passwordKey = (((SecretKeySpec) keystore.getKey(alias, masterPassword.toCharArray()))); newKeystore.setKeyEntry(alias, passwordKey, newMasterPassword.toCharArray(), null); } else if (alias.startsWith("keypair#")) { // a private key entry // Get the private key for the alias PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, masterPassword.toCharArray()); // Get the related public key's certificate chain Certificate[] certChain = keystore.getCertificateChain(alias); newKeystore.setKeyEntry(alias, privateKey, newMasterPassword.toCharArray(), certChain); } } /* * Do all entries at once, not reason to separate password & * key pair entries */ newKeystore.setEntry(alias, keystore.getEntry(alias, new KeyStore.PasswordProtection(masterPassword.toCharArray())), new KeyStore.PasswordProtection(newMasterPassword.toCharArray())); } try (FileOutputStream fos = new FileOutputStream(keystoreFile)) { newKeystore.store(fos, newMasterPassword.toCharArray()); } keystore = newKeystore; } /* * Truststore does not need to be re-encrypeted item by item as * entries there are not encrypted, just the whole truststore */ synchronized (truststore) { try (FileOutputStream fos = new FileOutputStream(truststoreFile)) { truststore.store(fos, newMasterPassword.toCharArray()); } } // Set the new master password as well masterPassword = newMasterPassword; } catch (Exception ex) { // rollback keystore = oldKeystore; truststore = oldTruststore; masterPassword = oldMasterPassword; saveKeystore(KEYSTORE); saveKeystore(TRUSTSTORE); String exMessage = "Failed to change maaster password - reverting to the old one"; logger.error(exMessage, ex); throw new CMException(exMessage); } }