SecretKeyEntry entry = (KeyStore.SecretKeyEntry)ks.getEntry(SOME_ALIAS,new KeyStore.PasswordProtection(SOME_PASSWORD)); SecretKey someKey = entry.getSecretKey();
private static KeyStore loadKeyCert(List<Buffer> keyValue, List<Buffer> certValue) throws Exception { if (keyValue.size() < certValue.size()) { throw new VertxException("Missing private key"); } else if (keyValue.size() > certValue.size()) { throw new VertxException("Missing X.509 certificate"); } final KeyStore keyStore = createEmptyKeyStore(); Iterator<Buffer> keyValueIt = keyValue.iterator(); Iterator<Buffer> certValueIt = certValue.iterator(); int index = 0; while (keyValueIt.hasNext() && certValueIt.hasNext()) { PrivateKey key = loadPrivateKey(keyValueIt.next()); Certificate[] chain = loadCerts(certValueIt.next()); keyStore.setEntry("dummy-entry-" + index++, new KeyStore.PrivateKeyEntry(key, chain), new KeyStore.PasswordProtection(DUMMY_PASSWORD.toCharArray())); } return keyStore; }
boolean verifySigned(File keystore, Certificate agentCertificate) { try { KeyStore store = KeyStore.getInstance("JKS"); FileInputStream inputStream = new FileInputStream(keystore); store.load(inputStream, PASSWORD_AS_CHAR_ARRAY); IOUtils.closeQuietly(inputStream); KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store.getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY)); Certificate intermediateCertificate = intermediateEntry.getCertificate(); agentCertificate.verify(intermediateCertificate.getPublicKey()); return true; } catch (Exception e) { return false; } }
@Override public CertificateAndKey load() { try { KeyStore.Entry entry; try { entry = keyStore.getEntry(privateKeyAlias, new KeyStore.PasswordProtection(keyStorePassword.toCharArray())); } catch (UnrecoverableEntryException e) { throw new CertificateSourceException("Unable to load private key with alias " + privateKeyAlias + " from KeyStore. Verify the KeyStore password is correct.", e); } if (entry == null) { throw new CertificateSourceException("Unable to find entry in keystore with alias: " + privateKeyAlias); } if (!(entry instanceof KeyStore.PrivateKeyEntry)) { throw new CertificateSourceException("Entry in KeyStore with alias " + privateKeyAlias + " did not contain a private key entry"); } KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) entry; PrivateKey privateKey = privateKeyEntry.getPrivateKey(); if (!(privateKeyEntry.getCertificate() instanceof X509Certificate)) { throw new CertificateSourceException("Certificate for private key in KeyStore was not an X509Certificate. Private key alias: " + privateKeyAlias + ". Certificate type: " + (privateKeyEntry.getCertificate() != null ? privateKeyEntry.getCertificate().getClass().getName() : null)); } X509Certificate x509Certificate = (X509Certificate) privateKeyEntry.getCertificate(); return new CertificateAndKey(x509Certificate, privateKey); } catch (KeyStoreException | NoSuchAlgorithmException e) { throw new CertificateSourceException("Error accessing keyStore", e); } }
@Override public SingleSignOnSessionFactory get() { KeyStore store = this.keyStore.get(); String alias = this.keyAlias; CredentialSource source = this.credentialSource.get(); try { if (!store.containsAlias(alias)) { throw UndertowLogger.ROOT_LOGGER.missingKeyStoreEntry(alias); } if (!store.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) { throw UndertowLogger.ROOT_LOGGER.keyStoreEntryNotPrivate(alias); } PasswordCredential credential = source.getCredential(PasswordCredential.class); if (credential == null) { throw UndertowLogger.ROOT_LOGGER.missingCredential(source.toString()); } ClearPassword password = credential.getPassword(ClearPassword.class); if (password == null) { throw UndertowLogger.ROOT_LOGGER.credentialNotClearPassword(credential.toString()); } KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) store.getEntry(alias, new KeyStore.PasswordProtection(password.getPassword())); KeyPair keyPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); Optional<SSLContext> context = Optional.ofNullable(this.sslContext).map(dependency -> dependency.get()); return new DefaultSingleSignOnSessionFactory(this.manager.get(), keyPair, connection -> context.ifPresent(ctx -> connection.setSSLSocketFactory(ctx.getSocketFactory()))); } catch (GeneralSecurityException | IOException e) { throw new IllegalArgumentException(e); } } }
store.setEntry(ALIAS, new KeyStore.SecretKeyEntry(new SecretKeySpec(KEY, "AES")), new KeyStore.PasswordProtection(PASSWORD.toCharArray()));
@Override public CipherAuthToken apply(String authValue) { KeyStore store = this.keyStore.get(); String alias = this.keyAlias; try { if (!store.containsAlias(alias)) { throw JGroupsLogger.ROOT_LOGGER.keyEntryNotFound(alias); } if (!store.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) { throw JGroupsLogger.ROOT_LOGGER.unexpectedKeyStoreEntryType(alias, KeyStore.PrivateKeyEntry.class.getSimpleName()); } PasswordCredential credential = this.keyCredentialSource.get().getCredential(PasswordCredential.class); if (credential == null) { throw JGroupsLogger.ROOT_LOGGER.unexpectedCredentialSource(); } ClearPassword password = credential.getPassword(ClearPassword.class); if (password == null) { throw JGroupsLogger.ROOT_LOGGER.unexpectedCredentialSource(); } KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) store.getEntry(alias, new KeyStore.PasswordProtection(password.getPassword())); KeyPair pair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); Cipher cipher = Cipher.getInstance(this.transformation); return new CipherAuthToken(cipher, pair, authValue.getBytes(StandardCharsets.UTF_8)); } catch (GeneralSecurityException | IOException e) { throw new IllegalArgumentException(e); } } }
@Override public void accept(P protocol) { KeyStore store = this.keyStore.get(); String alias = this.keyAlias; try { if (!store.containsAlias(alias)) { throw JGroupsLogger.ROOT_LOGGER.keyEntryNotFound(alias); } PasswordCredential credential = this.credentialSource.get().getCredential(PasswordCredential.class); if (credential == null) { throw JGroupsLogger.ROOT_LOGGER.unexpectedCredentialSource(); } ClearPassword password = credential.getPassword(ClearPassword.class); if (password == null) { throw JGroupsLogger.ROOT_LOGGER.unexpectedCredentialSource(); } if (!store.entryInstanceOf(alias, this.entryClass)) { throw JGroupsLogger.ROOT_LOGGER.unexpectedKeyStoreEntryType(alias, this.entryClass.getSimpleName()); } KeyStore.Entry entry = store.getEntry(alias, new KeyStore.PasswordProtection(password.getPassword())); protocol.setKeyStoreEntry(this.entryClass.cast(entry)); } catch (KeyStoreException | IOException | NoSuchAlgorithmException | UnrecoverableEntryException e) { throw new IllegalArgumentException(e); } } }
/** * Initialisation if a supplied key is defined in the properties. This supplied key must be in a keystore which * can be generated using the keystoreGenerator file in demos. The keystore must be on the classpath to find it. */ protected void readSecretKeyFromKeystore() throws Exception { // must not use default keystore type - as it does not support secret keys KeyStore store=KeyStore.getInstance(keystore_type != null? keystore_type : KeyStore.getDefaultType()); if(key_password == null && store_password != null) { key_password=store_password; log.debug("%s: key_password used is same as store_password", local_addr); } try (InputStream inputStream = getKeyStoreSource()) { store.load(inputStream, store_password.toCharArray()); } // loaded keystore - get the key if (!store.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)) { throw new Exception("Key '" + alias + "' from keystore " + keystore_name + " is not a secret key"); } KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry) store.getEntry(alias, new KeyStore.PasswordProtection(key_password.toCharArray())); if (entry == null) { throw new Exception("Key '" + alias + "' not found in keystore " + keystore_name); } this.setKeyStoreEntry(entry); }
/** * Used during setup to get the certification from the keystore and encrypt the auth_value with * the private key */ public void setCertificate() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnrecoverableEntryException { KeyStore store = KeyStore.getInstance(this.keystore_type); InputStream inputStream=Thread.currentThread().getContextClassLoader().getResourceAsStream(this.keystore_path); if(inputStream == null) inputStream=new FileInputStream(this.keystore_path); store.load(inputStream, this.keystore_password); this.cipher = Cipher.getInstance(this.cipher_type); this.certificate = (X509Certificate) store.getCertificate(this.cert_alias); log.debug("certificate = " + this.certificate.toString()); this.cipher.init(Cipher.ENCRYPT_MODE, this.certificate); this.encryptedToken = this.cipher.doFinal(this.auth_value.getBytes()); KeyStore.PrivateKeyEntry privateKey = (KeyStore.PrivateKeyEntry) store.getEntry( this.cert_alias, new KeyStore.PasswordProtection(this.cert_password)); this.certPrivateKey = privateKey.getPrivateKey(); this.valueSet=true; } }
DEFAULT_MASTER_KEY_NAME, new KeyStore.SecretKeyEntry(key), new KeyStore.PasswordProtection(KEYSTORE_PASSWORD.toCharArray()));
private KeystoreWrapper(InputStream inputStream, String type, String password) throws EsHadoopSecurityException, IOException { Assert.notNull(password, "Password should not be null"); try { char[] pwd = password.toCharArray(); protection = new KeyStore.PasswordProtection(pwd); keyStore = KeyStore.getInstance(type); keyStore.load(inputStream, pwd); } catch (CertificateException e) { throw new EsHadoopSecurityException("Could not create keystore", e); } catch (NoSuchAlgorithmException e) { throw new EsHadoopSecurityException("Could not create keystore", e); } catch (KeyStoreException e) { throw new EsHadoopSecurityException("Could not create keystore", e); } }
/** * Generate a set of AES keys for the store. The key ids will simple be (startOffset ... startOffset + numKeys). * @param numKeys Number of keys to generate * @param startOffset ID to start generating keys with * @throws IOException If there is an error serializing the keystore back to disk * @throws KeyStoreException If there is an error serializing the keystore back to disk */ public void generateAesKeys(int numKeys, int startOffset) throws IOException, KeyStoreException { for (int i = 1; i <= numKeys; i++) { SecretKey key = generateKey(); ks.setEntry(String.valueOf(i + startOffset), new KeyStore.SecretKeyEntry(key), new KeyStore.PasswordProtection(password)); } saveKeystore(); }
@Override public void setSecretKey(String alias, char[] key) throws IOException { assertActivatedKeyStore(); SecretKey mySecretKey = new SecretKeySpec(toBytes(key), "PBE"); KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(mySecretKey); char[] passwd = securityManager.getMasterPassword(); try { ks.setEntry(alias, skEntry, new KeyStore.PasswordProtection(passwd)); } catch (KeyStoreException e) { throw new IOException(e); } finally { securityManager.disposePassword(passwd); } }
private KeyStore.ProtectionParameter convertParameter(final CredentialStore.ProtectionParameter protectionParameter) throws CredentialStoreException { // only one conversion is really possible. if (protectionParameter == null) { return convertParameter(this.protectionParameter); } else if (protectionParameter instanceof CredentialStore.CredentialSourceProtectionParameter) { final CredentialSource credentialSource = ((CredentialStore.CredentialSourceProtectionParameter) protectionParameter).getCredentialSource(); try { return credentialSource.applyToCredential(PasswordCredential.class, c -> c.getPassword().castAndApply(ClearPassword.class, p -> new KeyStore.PasswordProtection(p.getPassword()))); } catch (IOException e) { throw log.cannotAcquireCredentialFromStore(e); } } else { throw log.invalidProtectionParameter(protectionParameter); } }
/** * Returns an entry from the KeyStore with the given alias * * @param alias the alias * @return an entry from the KeyStore with the given alias * @throws GeneralSecurityException if there is a problem retrieving the entry */ public KeyStore.Entry getEntry(String alias) throws GeneralSecurityException { String keyPassword = getKeyPassword(); return keyStore.getEntry(alias, new KeyStore.PasswordProtection(keyPassword == null ? null : keyPassword.toCharArray())); }
public Registration createAgentCertificate(final File authorityKeystore, String agentHostname) { Date epoch = new Date(0); KeyPair agentKeyPair = generateKeyPair(); try { KeyStore store = loadOrCreateCAKeyStore(authorityKeystore); KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store.getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY)); X509Certificate[] chain = new X509Certificate[3]; chain[2] = (X509Certificate) store.getCertificate("ca-cert"); chain[1] = (X509Certificate) intermediateEntry.getCertificate(); chain[0] = createAgentCertificate(agentKeyPair.getPublic(), intermediateEntry.getPrivateKey(), chain[1].getPublicKey(), agentHostname, epoch); return new Registration(agentKeyPair.getPrivate(), chain); } catch (Exception e) { throw bomb("Couldn't create agent certificate", e); } }
private void fetchStorageSecretKey(String keyAlias, char[] keyPassword) throws CertificateException, NoSuchAlgorithmException, IOException, CredentialStoreException, UnrecoverableEntryException, KeyStoreException { KeyStore.Entry entry = storageSecretKeyStore.getEntry(keyAlias, new KeyStore.PasswordProtection(keyPassword)); if (entry == null) { throw log.externalStorageKeyDoesNotExist(keyAlias); } if (! (entry instanceof KeyStore.SecretKeyEntry)) { throw log.wrongTypeOfExternalStorageKey(keyAlias); } storageSecretKey = ((KeyStore.SecretKeyEntry) entry).getSecretKey(); }
public void engineSetKeyEntry(final String alias, final Key key, final char[] password, final Certificate[] chain) throws KeyStoreException { if (key instanceof Password) { engineSetEntry(alias, new PasswordEntry((Password) key), password == null ? null : new KeyStore.PasswordProtection(password)); } else { delegate.setKeyEntry(alias, key, password, chain); } }
public void storeCACertificate(File storeFile, String password, Certificate caCertificate, Registration entry) throws Exception { lazyLoadedStore = KeyStore.getInstance(KEYSTORE_TYPE); loadStore(lazyLoadedStore); lazyLoadedStore.setCertificateEntry("ca-cert", caCertificate); lazyLoadedStore.setEntry("ca-intermediate", entry.asKeyStoreEntry(), new KeyStore.PasswordProtection(password.toCharArray())); writeStore(storeFile, password); }