Example usage for java.security KeyManagementException KeyManagementException

List of usage examples for java.security KeyManagementException KeyManagementException

Introduction

In this page you can find the example usage for java.security KeyManagementException KeyManagementException.

Prototype

public KeyManagementException(Throwable cause) 

Source Link

Document

Creates a KeyManagementException with the specified cause and a detail message of (cause==null ?

Usage

From source file:org.apache.nifi.provenance.AESProvenanceEventEncryptor.java

/**
 * Returns a valid key identifier for this encryptor (valid for encryption and decryption) or throws an exception if none are available.
 *
 * @return the key ID/*from w  w  w  . ja  v  a 2s  .  c o  m*/
 * @throws KeyManagementException if no available key IDs are valid for both operations
 */
@Override
public String getNextKeyId() throws KeyManagementException {
    if (keyProvider != null) {
        List<String> availableKeyIds = keyProvider.getAvailableKeyIds();
        if (!availableKeyIds.isEmpty()) {
            return availableKeyIds.get(0);
        }
    }
    throw new KeyManagementException("No available key IDs");
}

From source file:org.apache.nifi.provenance.CryptoUtils.java

/**
 * Returns a {@link SecretKey} formed from the hexadecimal key bytes (validity is checked).
 *
 * @param keyHex the key in hex form//from www  . j a  v  a2s.c om
 * @return the SecretKey
 */
public static SecretKey formKeyFromHex(String keyHex) throws KeyManagementException {
    if (keyIsValid(keyHex)) {
        return new SecretKeySpec(Hex.decode(keyHex), "AES");
    } else {
        throw new KeyManagementException("The provided key material is not valid");
    }
}

From source file:org.apache.nifi.provenance.CryptoUtils.java

/**
 * Returns a map containing the key IDs and the parsed key from a key provider definition file.
 * The values in the file are decrypted using the master key provided. If the file is missing or empty,
 * cannot be read, or if no valid keys are read, a {@link KeyManagementException} will be thrown.
 *
 * @param filepath  the key definition file path
 * @param masterKey the master key used to decrypt each key definition
 * @return a Map of key IDs to SecretKeys
 * @throws KeyManagementException if the file is missing or invalid
 *///from ww w  .  ja v  a 2 s . com
public static Map<String, SecretKey> readKeys(String filepath, SecretKey masterKey)
        throws KeyManagementException {
    Map<String, SecretKey> keys = new HashMap<>();

    if (StringUtils.isBlank(filepath)) {
        throw new KeyManagementException("The key provider file is not present and readable");
    }
    File file = new File(filepath);
    if (!file.exists() || !file.canRead()) {
        throw new KeyManagementException("The key provider file is not present and readable");
    }

    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        AESKeyedCipherProvider masterCipherProvider = new AESKeyedCipherProvider();

        String line;
        int l = 1;
        while ((line = br.readLine()) != null) {
            String[] components = line.split("=", 2);
            if (components.length != 2 || StringUtils.isAnyEmpty(components)) {
                logger.warn("Line " + l + " is not properly formatted -- keyId=Base64EncodedKey...");
            }
            String keyId = components[0];
            if (StringUtils.isNotEmpty(keyId)) {
                try {
                    byte[] base64Bytes = Base64.getDecoder().decode(components[1]);
                    byte[] ivBytes = Arrays.copyOfRange(base64Bytes, 0, IV_LENGTH);

                    Cipher masterCipher = null;
                    try {
                        masterCipher = masterCipherProvider.getCipher(EncryptionMethod.AES_GCM, masterKey,
                                ivBytes, false);
                    } catch (Exception e) {
                        throw new KeyManagementException(
                                "Error building cipher to decrypt FileBaseKeyProvider definition at "
                                        + filepath,
                                e);
                    }
                    byte[] individualKeyBytes = masterCipher
                            .doFinal(Arrays.copyOfRange(base64Bytes, IV_LENGTH, base64Bytes.length));

                    SecretKey key = new SecretKeySpec(individualKeyBytes, "AES");
                    logger.debug("Read and decrypted key for " + keyId);
                    if (keys.containsKey(keyId)) {
                        logger.warn("Multiple key values defined for " + keyId + " -- using most recent value");
                    }
                    keys.put(keyId, key);
                } catch (IllegalArgumentException e) {
                    logger.error("Encountered an error decoding Base64 for " + keyId + ": "
                            + e.getLocalizedMessage());
                } catch (BadPaddingException | IllegalBlockSizeException e) {
                    logger.error("Encountered an error decrypting key for " + keyId + ": "
                            + e.getLocalizedMessage());
                }
            }
            l++;
        }

        if (keys.isEmpty()) {
            throw new KeyManagementException("The provided file contained no valid keys");
        }

        logger.info("Read " + keys.size() + " keys from FileBasedKeyProvider " + filepath);
        return keys;
    } catch (IOException e) {
        throw new KeyManagementException("Error reading FileBasedKeyProvider definition at " + filepath, e);
    }

}

From source file:org.apache.nifi.provenance.EncryptedWriteAheadProvenanceRepository.java

private KeyProvider buildKeyProvider(SecretKey masterKey) throws KeyManagementException {
    RepositoryConfiguration config = super.getConfig();
    if (config == null) {
        throw new KeyManagementException("The repository configuration is missing");
    }/*  ww w  .ja v a2 s.  com*/

    final String implementationClassName = config.getKeyProviderImplementation();
    if (implementationClassName == null) {
        throw new KeyManagementException(
                "Cannot create Key Provider because the NiFi Properties is missing the following property: "
                        + NiFiProperties.PROVENANCE_REPO_ENCRYPTION_KEY_PROVIDER_IMPLEMENTATION_CLASS);
    }

    return KeyProviderFactory.buildKeyProvider(implementationClassName, config.getKeyProviderLocation(),
            config.getKeyId(), config.getEncryptionKeys(), masterKey);
}

From source file:org.apache.nifi.provenance.EncryptedWriteAheadProvenanceRepository.java

private static SecretKey getMasterKey() throws KeyManagementException {
    try {//  w ww. ja v a2 s . c  o  m
        // Get the master encryption key from bootstrap.conf
        String masterKeyHex = NiFiPropertiesLoader.extractKeyFromBootstrapFile();
        return new SecretKeySpec(Hex.decodeHex(masterKeyHex.toCharArray()), "AES");
    } catch (IOException | DecoderException e) {
        logger.error("Encountered an error: ", e);
        throw new KeyManagementException(e);
    }
}

From source file:org.apache.nifi.security.kms.CryptoUtils.java

static String handleLegacyPackages(String implementationClassName) throws KeyManagementException {
    if (org.apache.nifi.util.StringUtils.isBlank(implementationClassName)) {
        throw new KeyManagementException(
                "Invalid key provider implementation provided: " + implementationClassName);
    }/* w  w  w. ja va 2s  .  c  om*/
    if (implementationClassName.equalsIgnoreCase(LEGACY_SKP_FQCN)) {
        return StaticKeyProvider.class.getName();
    } else if (implementationClassName.equalsIgnoreCase(LEGACY_FBKP_FQCN)) {
        return FileBasedKeyProvider.class.getName();
    } else {
        return implementationClassName;
    }
}

From source file:org.apache.nifi.security.kms.CryptoUtils.java

/**
 * Returns a map containing the key IDs and the parsed key from a key provider definition file.
 * The values in the file are decrypted using the master key provided. If the file is missing or empty,
 * cannot be read, or if no valid keys are read, a {@link KeyManagementException} will be thrown.
 *
 * @param filepath  the key definition file path
 * @param masterKey the master key used to decrypt each key definition
 * @return a Map of key IDs to SecretKeys
 * @throws KeyManagementException if the file is missing or invalid
 *///from  ww  w .  j  a  va2 s .co  m
public static Map<String, SecretKey> readKeys(String filepath, SecretKey masterKey)
        throws KeyManagementException {
    Map<String, SecretKey> keys = new HashMap<>();

    if (StringUtils.isBlank(filepath)) {
        throw new KeyManagementException("The key provider file is not present and readable");
    }
    if (masterKey == null) {
        throw new KeyManagementException("The master key must be provided to decrypt the individual keys");
    }

    File file = new File(filepath);
    if (!file.exists() || !file.canRead()) {
        throw new KeyManagementException("The key provider file is not present and readable");
    }

    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        AESKeyedCipherProvider masterCipherProvider = new AESKeyedCipherProvider();

        String line;
        int l = 1;
        while ((line = br.readLine()) != null) {
            String[] components = line.split("=", 2);
            if (components.length != 2 || StringUtils.isAnyEmpty(components)) {
                logger.warn("Line " + l + " is not properly formatted -- keyId=Base64EncodedKey...");
            }
            String keyId = components[0];
            if (StringUtils.isNotEmpty(keyId)) {
                try {
                    byte[] base64Bytes = Base64.getDecoder().decode(components[1]);
                    byte[] ivBytes = Arrays.copyOfRange(base64Bytes, 0, IV_LENGTH);

                    Cipher masterCipher = null;
                    try {
                        masterCipher = masterCipherProvider.getCipher(EncryptionMethod.AES_GCM, masterKey,
                                ivBytes, false);
                    } catch (Exception e) {
                        throw new KeyManagementException(
                                "Error building cipher to decrypt FileBaseKeyProvider definition at "
                                        + filepath,
                                e);
                    }
                    byte[] individualKeyBytes = masterCipher
                            .doFinal(Arrays.copyOfRange(base64Bytes, IV_LENGTH, base64Bytes.length));

                    SecretKey key = new SecretKeySpec(individualKeyBytes, "AES");
                    logger.debug("Read and decrypted key for " + keyId);
                    if (keys.containsKey(keyId)) {
                        logger.warn("Multiple key values defined for " + keyId + " -- using most recent value");
                    }
                    keys.put(keyId, key);
                } catch (IllegalArgumentException e) {
                    logger.error("Encountered an error decoding Base64 for " + keyId + ": "
                            + e.getLocalizedMessage());
                } catch (BadPaddingException | IllegalBlockSizeException e) {
                    logger.error("Encountered an error decrypting key for " + keyId + ": "
                            + e.getLocalizedMessage());
                }
            }
            l++;
        }

        if (keys.isEmpty()) {
            throw new KeyManagementException("The provided file contained no valid keys");
        }

        logger.info("Read " + keys.size() + " keys from FileBasedKeyProvider " + filepath);
        return keys;
    } catch (IOException e) {
        throw new KeyManagementException("Error reading FileBasedKeyProvider definition at " + filepath, e);
    }

}

From source file:org.codice.ddf.cxf.client.impl.SecureCxfClientFactoryImpl.java

@SuppressWarnings("squid:S3776")
private void configureConduit(ClientConfiguration clientConfig) {
    HTTPConduit httpConduit = clientConfig.getHttpConduit();
    if (httpConduit == null) {
        LOGGER.info("HTTPConduit was null for {}. Unable to configure security.", this);
        return;//from   ww w.j  a v  a  2s. c o  m
    }

    if (allowRedirects) {
        HTTPClientPolicy clientPolicy = httpConduit.getClient();
        if (clientPolicy != null) {
            clientPolicy.setAutoRedirect(true);
            Bus bus = clientConfig.getBus();
            if (bus != null) {
                bus.getProperties().put(AUTO_REDIRECT_ALLOW_REL_URI, true);
                bus.getProperties().put(AUTO_REDIRECT_MAX_SAME_URI_COUNT, getSameUriRedirectMax());
            }
        }
    }

    TLSClientParameters tlsParams = httpConduit.getTlsClientParameters();
    if (tlsParams == null) {
        tlsParams = new TLSClientParameters();
    }

    tlsParams.setDisableCNCheck(disableCnCheck);

    tlsParams.setUseHttpsURLConnectionDefaultHostnameVerifier(!disableCnCheck);
    String cipherSuites = System.getProperty("https.cipherSuites");
    if (cipherSuites != null) {
        tlsParams.setCipherSuites(Arrays.asList(cipherSuites.split(",")));
    }

    KeyStore keyStore = null;
    KeyStore trustStore = null;
    try {
        keyStore = SecurityConstants.newKeystore();
        trustStore = SecurityConstants.newTruststore();
    } catch (KeyStoreException e) {
        LOGGER.debug("Unable to create keystore instance of type {}",
                System.getProperty(SecurityConstants.KEYSTORE_TYPE), e);
    }
    Path keyStoreFile;
    if (keyInfo != null && StringUtils.isNotBlank(keyInfo.getKeystorePath())) {
        keyStoreFile = Paths.get(keyInfo.getKeystorePath());
    } else {
        keyStoreFile = Paths.get(SecurityConstants.getKeystorePath());
    }

    Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath());
    String ddfHome = System.getProperty("ddf.home");
    if (ddfHome != null) {
        Path ddfHomePath = Paths.get(ddfHome);
        if (!keyStoreFile.isAbsolute()) {
            keyStoreFile = Paths.get(ddfHomePath.toString(), keyStoreFile.toString());
        }
        if (!trustStoreFile.isAbsolute()) {
            trustStoreFile = Paths.get(ddfHomePath.toString(), trustStoreFile.toString());
        }
    }
    String keyStorePassword = SecurityConstants.getKeystorePassword();
    String trustStorePassword = SecurityConstants.getTruststorePassword();
    if (!Files.isReadable(keyStoreFile) || !Files.isReadable(trustStoreFile)) {
        LOGGER.debug("Unable to read system key/trust store files: [ {} ] [ {} ]", keyStoreFile,
                trustStoreFile);
        return;
    }
    try (InputStream kfis = Files.newInputStream(keyStoreFile)) {
        if (keyStore != null) {
            keyStore.load(kfis, keyStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system key file.", e);
    }
    try (InputStream tfis = Files.newInputStream(trustStoreFile)) {
        if (trustStore != null) {
            trustStore.load(tfis, trustStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system trust file.", e);
    }

    KeyManager[] keyManagers = null;
    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
        keyManagers = keyManagerFactory.getKeyManagers();
        tlsParams.setKeyManagers(keyManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
        LOGGER.debug("Unable to initialize KeyManagerFactory.", e);
    }

    TrustManager[] trustManagers = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        trustManagers = trustManagerFactory.getTrustManagers();
        tlsParams.setTrustManagers(trustManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.debug("Unable to initialize TrustManagerFactory.", e);
    }

    if (keyInfo != null) {
        LOGGER.trace("Using keystore file: {}, alias: {}", keyStoreFile, keyInfo.getAlias());
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(false);
        tlsParams.setCertAlias(keyInfo.getAlias());
        try {
            if (keyManagers == null) {
                throw new KeyManagementException("keyManagers was null");
            }

            boolean validProtocolFound = false;
            String validProtocolsStr = System.getProperty("jdk.tls.client.protocols");
            if (StringUtils.isNotBlank(validProtocolsStr)) {
                String[] validProtocols = validProtocolsStr.split(",");
                for (String validProtocol : validProtocols) {
                    if (validProtocol.equals(sslProtocol)) {
                        validProtocolFound = true;
                        break;
                    }
                }
                if (!validProtocolFound) {
                    LOGGER.error("{} is not in list of valid SSL protocols {}", sslProtocol, validProtocolsStr);
                }

            } else {
                validProtocolFound = true;
            }
            if (validProtocolFound) {
                tlsParams.setSSLSocketFactory(
                        getSSLSocketFactory(sslProtocol, keyInfo.getAlias(), keyManagers, trustManagers));
            }
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            LOGGER.debug("Unable to override default SSL Socket Factory", e);
        }
    } else {
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(true);
        tlsParams.setCertAlias(SystemBaseUrl.INTERNAL.getHost());
    }

    httpConduit.setTlsClientParameters(tlsParams);
}