List of usage examples for java.security KeyStore setEntry
public final void setEntry(String alias, Entry entry, ProtectionParameter protParam) throws KeyStoreException
From source file:net.theblackchamber.crypto.util.KeystoreUtils.java
/** * Method which will generate a random AES key and add it to a keystore with * the entry name provided./* w ww . j a v a 2 s.c o m*/ * * @param config * Configuration for generation of key. * @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws CertificateException * @throws IOException */ public static void generateAESSecretKey(KeyConfig config) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { if (config == null || config.getKeyStoreFile() == null || StringUtils.isEmpty(config.getKeyEntryName()) || config.getAlgorithm() == null) { throw new KeyStoreException("Missing parameters, unable to create keystore."); } SecureRandom random = new SecureRandom(); KeyGenerator keygen = KeyGenerator.getInstance(config.getAlgorithm().toString(), new BouncyCastleProvider()); keygen.init(config.getKeySize(), random); SecretKey key = keygen.generateKey(); KeyStore keyStore = KeyStore.getInstance("JCEKS"); FileInputStream fis = null; if (config.getKeyStoreFile().exists() && FileUtils.sizeOf(config.getKeyStoreFile()) > 0) { fis = new FileInputStream(config.getKeyStoreFile()); } keyStore.load(fis, config.getKeyStorePassword().toCharArray()); KeyStore.ProtectionParameter protectionParameter = new KeyStore.PasswordProtection( config.getKeyStorePassword().toCharArray()); KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(key); keyStore.setEntry(config.getKeyEntryName(), secretKeyEntry, protectionParameter); if (fis != null) { fis.close(); } FileOutputStream fos = new FileOutputStream(config.getKeyStoreFile()); keyStore.store(fos, config.getKeyStorePassword().toCharArray()); fos.close(); }
From source file:org.apache.hadoop.hbase.io.crypto.TestKeyStoreKeyProvider.java
@BeforeClass public static void setUp() throws Exception { KEY = MessageDigest.getInstance("SHA-256").digest(ALIAS.getBytes()); // Create a JKECS store containing a test secret key KeyStore store = KeyStore.getInstance("JCEKS"); store.load(null, PASSWORD.toCharArray()); store.setEntry(ALIAS, new KeyStore.SecretKeyEntry(new SecretKeySpec(KEY, "AES")), new KeyStore.PasswordProtection(PASSWORD.toCharArray())); // Create the test directory String dataDir = TEST_UTIL.getDataTestDir().toString(); new File(dataDir).mkdirs(); // Write the keystore file storeFile = new File(dataDir, "keystore.jks"); FileOutputStream os = new FileOutputStream(storeFile); try {// w ww. jav a 2s . c om store.store(os, PASSWORD.toCharArray()); } finally { os.close(); } // Write the password file Properties p = new Properties(); p.setProperty(ALIAS, PASSWORD); passwordFile = new File(dataDir, "keystore.pw"); os = new FileOutputStream(passwordFile); try { p.store(os, ""); } finally { os.close(); } }
From source file:org.apache.metron.dataservices.auth.AuthToken.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("keystoreFile", true, "Keystore File"); options.addOption("keystorePassword", true, "Keystore Password"); options.addOption("authTokenAlias", true, ""); CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); try {/*from w ww . j a va2s . c o m*/ KeyStore ks = KeyStore.getInstance("JCEKS"); String keystorePassword = cmd.getOptionValue("keystorePassword"); String keystoreFile = cmd.getOptionValue("keystoreFile"); String authTokenAlias = cmd.getOptionValue("authTokenAlias"); ks.load(null, keystorePassword.toCharArray()); // generate a key and store it in the keystore... KeyGenerator keyGen = KeyGenerator.getInstance("AES"); SecretKey key = keyGen.generateKey(); KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection( keystorePassword.toCharArray()); KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(key); ks.setEntry(authTokenAlias, skEntry, protParam); java.io.FileOutputStream fos = null; try { fos = new java.io.FileOutputStream(keystoreFile); ks.store(fos, keystorePassword.toCharArray()); } finally { if (fos != null) { fos.close(); } } System.out.println("done"); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.taverna.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. *//* w w w . j a v a 2s . co m*/ @Override public void changeMasterPassword(String newMasterPassword) throws CMException { // Need to make sure we are initialized before we do anything else // as 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)); } }
From source file:org.commonjava.util.jhttpc.INTERNAL.util.SSLUtils.java
public static KeyStore decodePEMTrustStore(final String pemContent, final String aliasPrefix) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException { Logger logger = LoggerFactory.getLogger(SSLUtils.class); final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null);//w w w. jav a 2 s. co m final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); final List<String> lines = readLines(pemContent); final StringBuilder current = new StringBuilder(); final List<String> entries = new ArrayList<String>(); for (String line : lines) { if (line == null) { continue; } if (line.startsWith("-----BEGIN")) { current.setLength(0); } else if (line.startsWith("-----END")) { entries.add(current.toString()); } else { current.append(line); } } logger.trace("Found {} entries to decode.", entries.size()); int i = 0; for (final String entry : entries) { logger.trace("Decoding certificate info from:\n\n{}\n\n", entry); final byte[] data = decodeBase64(entry); final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data)); X509Certificate cert = (X509Certificate) c; Set<String> aliases = new HashSet<String>(); if (i < 1) { aliases.add(aliasPrefix); } else { aliases.add(aliasPrefix + i); } extractAliases(cert, aliases); KeyStore.TrustedCertificateEntry ksEntry = new KeyStore.TrustedCertificateEntry(cert); for (String alias : aliases) { ks.setEntry(alias, ksEntry, null); logger.trace("Storing trusted cert under alias: {}\n with DN: {}", alias, cert.getSubjectDN().getName()); } logger.trace("Certificate added."); i++; } return ks; }
From source file:org.jumpmind.security.SecurityService.java
protected SecretKey getSecretKey() throws Exception { String password = getKeyStorePassword(); KeyStore.ProtectionParameter param = new KeyStore.PasswordProtection(password.toCharArray()); KeyStore ks = getKeyStore(password); KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry) ks .getEntry(SecurityConstants.ALIAS_SYM_SECRET_KEY, param); if (entry == null) { log.debug("Generating secret key"); entry = new KeyStore.SecretKeyEntry(getDefaultSecretKey()); ks.setEntry(SecurityConstants.ALIAS_SYM_SECRET_KEY, entry, param); saveKeyStore(ks, password);//w ww. java 2 s. c o m } else { log.debug("Retrieving secret key"); } return entry.getSecretKey(); }
From source file:org.kuali.rice.ksb.security.admin.service.impl.JavaSecurityManagementServiceImpl.java
public KeyStore generateClientKeystore(String alias, String clientPassphrase) throws GeneralSecurityException { if (isAliasInKeystore(alias)) { throw new KeyStoreException("Alias '" + alias + "' already exists in module keystore"); }/* w w w . j a v a 2s .co m*/ // Certificate[] clientCertificateChain = {}; // PrivateKey clientPrivateKey = null; KeyStore ks = null; try { // generate a key pair for the client KeyPairGenerator keyGen = KeyPairGenerator.getInstance(CLIENT_KEY_GENERATOR_ALGORITHM); // SecureRandom random = SecureRandom.getInstance(CLIENT_SECURE_RANDOM_ALGORITHM); keyGen.initialize(CLIENT_KEY_PAIR_KEY_SIZE); // keyGen.initialize(new RSAKeyGenParameterSpec(512,RSAKeyGenParameterSpec.F0)); KeyPair pair = keyGen.generateKeyPair(); // PublicKey clientPublicKey = pair.getPublic(); // clientPrivateKey = pair.getPrivate(); // // generate the Certificate // X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); //// X509Name nameInfo = new X509Name(false,"CN=" + alias); // certificateGenerator.setSignatureAlgorithm("MD5WithRSA"); // certificateGenerator.setSerialNumber(new java.math.BigInteger("1")); // X509Principal nameInfo = new X509Principal("CN=" + alias); // certificateGenerator.setIssuerDN(nameInfo); // certificateGenerator.setSubjectDN(nameInfo); // note: same as issuer // certificateGenerator.setNotBefore(new Date()); // Calendar c = Calendar.getInstance(); // c.add(Calendar.DATE, CLIENT_CERT_EXPIRATION_DAYS); // certificateGenerator.setNotAfter(c.getTime()); // certificateGenerator.setPublicKey(clientPublicKey); // X509Certificate cert = certificateGenerator.generateX509Certificate(clientPrivateKey); // clientCertificateChain = new Certificate[]{cert}; // // // generate client keyStore file // ks = KeyStore.getInstance(getModuleKeyStoreType()); // ks.load(null, clientPassphrase.toCharArray()); // // set client private key on keyStore file // ks.setEntry(alias, new KeyStore.PrivateKeyEntry(clientPrivateKey, clientCertificateChain), new KeyStore.PasswordProtection(clientPassphrase.toCharArray())); Certificate cert = generateCertificate(pair, alias); ks = generateKeyStore(cert, pair.getPrivate(), alias, clientPassphrase); // set the module certificate on the client keyStore file ks.setEntry(getModuleKeyStoreAlias(), new KeyStore.TrustedCertificateEntry(getCertificate(getModuleKeyStoreAlias())), null); // add the client certificate to the module keyStore addClientCertificateToModuleKeyStore(alias, cert); return ks; } catch (IOException e) { throw new RuntimeException("Could not create new KeyStore", e); } }
From source file:org.kuali.rice.ksb.security.admin.service.impl.JavaSecurityManagementServiceImpl.java
protected KeyStore generateKeyStore(Certificate cert, PrivateKey privateKey, String alias, String keyStorePassword) throws GeneralSecurityException, IOException { KeyStore ks = KeyStore.getInstance(getModuleKeyStoreType()); ks.load(null, keyStorePassword.toCharArray()); // set client private key on keyStore file ks.setEntry(alias, new KeyStore.PrivateKeyEntry(privateKey, new Certificate[] { cert }), new KeyStore.PasswordProtection(keyStorePassword.toCharArray())); return ks;//w w w . ja v a 2 s . c o m }
From source file:org.nuxeo.common.codec.Crypto.java
/** * Store a key in a keystore.<br>// w w w . j a v a 2s .c om * The keystore is created if it doesn't exist. * * @param keystorePath Path to the keystore * @param keystorePass Keystore password * @param keyAlias Key alias prefix. It must be suffixed with the algorithm ({@link SecretKey#getAlgorithm()} is * fine). * @param keyPass Key password * @param key * @throws GeneralSecurityException * @throws IOException * @see #IMPLEMENTED_ALGOS */ public static void setKeyInKeyStore(String keystorePath, char[] keystorePass, String keyAlias, char[] keyPass, SecretKey key) throws GeneralSecurityException, IOException { KeyStore keystore = KeyStore.getInstance("JCEKS"); if (!new File(keystorePath).exists()) { log.info("Creating a new JCEKS keystore at " + keystorePath); keystore.load(null); } else { try (InputStream keystoreStream = new FileInputStream(keystorePath)) { keystore.load(keystoreStream, keystorePass); } } KeyStore.SecretKeyEntry keyStoreEntry = new KeyStore.SecretKeyEntry(key); PasswordProtection keyPassword = new PasswordProtection(keyPass); keystore.setEntry(keyAlias, keyStoreEntry, keyPassword); try (OutputStream keystoreStream = new FileOutputStream(keystorePath)) { keystore.store(keystoreStream, keystorePass); } }
From source file:org.paxml.util.CryptoUtils.java
private static void setKey(KeyStore keyStore, String keyName, String keyPassword, String keyValue) { if (StringUtils.isBlank(keyName)) { keyName = DEFAULT_KEY_NAME;//from w w w . j a va 2s . c om } if (keyPassword == null) { keyPassword = DEFAULT_KEY_PASSWORD; } try { SecretKey secretKey = new SecretKeySpec(keyValue.getBytes(KEY_VALUE_ENCODING), KEY_TYPE); KeyStore.SecretKeyEntry keyStoreEntry = new KeyStore.SecretKeyEntry(secretKey); PasswordProtection _keyPassword = new PasswordProtection(keyPassword.toCharArray()); keyStore.setEntry(keyName, keyStoreEntry, _keyPassword); } catch (Exception e) { throw new PaxmlRuntimeException(e); } }