/** * 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())); }
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; } }
/** * Store data from {@link #dataKeyStore} to output stream. * * @param outputStream to store data to * @throws IOException if something goes wrong */ void store(OutputStream outputStream) throws IOException, GeneralSecurityException { ObjectOutputStream oos = new ObjectOutputStream(outputStream); oos.writeInt(VERSION); Enumeration<String> ksAliases = dataKeyStore.aliases(); while(ksAliases.hasMoreElements()) { String alias = ksAliases.nextElement(); KeyStore.Entry entry = dataKeyStore.getEntry(alias, convertParameter(protectionParameter)); if (entry instanceof KeyStore.SecretKeyEntry) { saveSecretKey(alias, oos, (KeyStore.SecretKeyEntry)entry); } else { throw log.unrecognizedEntryType(entry != null ? entry.getClass().getCanonicalName() : "null"); } } oos.flush(); oos.close(); }
private KeyStore.Entry getEntry(String name) { try { KeyStore.Entry entry = keyStore.getEntry(name, null); if (entry == null) { log.tracef("KeyStoreRealm: alias [%s] does not exist in KeyStore", name); } return entry; } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) { log.tracef(e, "KeyStoreRealm: Obtaining entry [%s] from KeyStore failed", name); return null; } }
/** * Construct a new instance. * * @param keyStore the key store to reference (must not be {@code null}) * @param alias the name of the key store entry to read from (must not be {@code null}) * @param protectionParameter the protection parameter to use to access the key store entry, or {@code null} for none */ public KeyStoreCredentialSource(final KeyStore keyStore, final String alias, final KeyStore.ProtectionParameter protectionParameter) { Assert.checkNotNullParam("keyStore", keyStore); Assert.checkNotNullParam("alias", alias); entryFactory = () -> keyStore.getEntry(alias, protectionParameter); }
/** * 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; } }
public KeyStore.Entry create() throws GeneralSecurityException { return keyStore.create().getEntry(alias, protectionParameter == null ? null : protectionParameter.create()); } }
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(); }
/** * 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); }
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); } }
public String getSecureSetting(String alias) throws EsHadoopSecurityException { try { if (!keyStore.containsAlias(alias)) { return null; } KeyStore.Entry entry = keyStore.getEntry(alias, protection); KeyStore.SecretKeyEntry secretKeyEntry = ((KeyStore.SecretKeyEntry) entry); return new String(secretKeyEntry.getSecretKey().getEncoded()); } catch (NoSuchAlgorithmException e) { throw new EsHadoopSecurityException(String.format("Could not read alias [%s] from keystore", alias), e); } catch (UnrecoverableEntryException e) { throw new EsHadoopSecurityException(String.format("Could not read alias [%s] from keystore", alias), e); } catch (KeyStoreException e) { throw new EsHadoopSecurityException(String.format("Could not read alias [%s] from keystore", alias), e); } }
public KeyStore.Entry engineGetEntry(final String alias, final KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { final KeyStore.Entry entry = delegate.getEntry(alias, protParam); if (entry instanceof KeyStore.SecretKeyEntry) { final SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry).getSecretKey(); if ("password".equals(secretKey.getAlgorithm())) { return new PasswordEntry(decoded(secretKey)); } } return entry; }
private void createKeyForTimeout() throws Exception { KeyStore.Entry entry=ks.getEntry(KEY_NAME, null); if (entry==null) { KeyGenParameterSpec spec= new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) .setUserAuthenticationRequired(true) .setUserAuthenticationValidityDurationSeconds(TIMEOUT_SECONDS) .build(); KeyGenerator keygen= KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE); keygen.init(spec); keygen.generateKey(); } }
private void createKey(String keyName, int timeout) throws Exception { KeyStore.Entry entry=ks.getEntry(keyName, null); if (entry==null) { KeyGenParameterSpec spec= new KeyGenParameterSpec.Builder(keyName, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) .setUserAuthenticationRequired(true) .setUserAuthenticationValidityDurationSeconds(timeout) .setRandomizedEncryptionRequired(false) .build(); KeyGenerator keygen= KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE); keygen.init(spec); keygen.generateKey(); } } }
private void createKey(KeyStore ks, String keyName, int timeout) throws Exception { KeyStore.Entry entry=ks.getEntry(keyName, null); if (entry==null) { KeyGenParameterSpec spec= new KeyGenParameterSpec.Builder(keyName, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) .setUserAuthenticationRequired(true) .setUserAuthenticationValidityDurationSeconds(timeout) .setRandomizedEncryptionRequired(false) .build(); KeyGenerator keygen= KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE); keygen.init(spec); keygen.generateKey(); } }
@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); } } }
@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); } } }
@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); } }
KeyStore.Entry trustStoreEntry = trustStore.getEntry(alias, null); if (trustStoreEntry instanceof KeyStore.TrustedCertificateEntry) { Certificate trustedCertificate = ((KeyStore.TrustedCertificateEntry) trustStoreEntry).getTrustedCertificate();