Search in sources :

Example 1 with KeyDerivationFunction

use of org.apache.nifi.security.util.KeyDerivationFunction in project nifi by apache.

the class EncryptContent method onTrigger.

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }
    final ComponentLog logger = getLogger();
    final String method = context.getProperty(ENCRYPTION_ALGORITHM).getValue();
    final EncryptionMethod encryptionMethod = EncryptionMethod.valueOf(method);
    final String providerName = encryptionMethod.getProvider();
    final String algorithm = encryptionMethod.getAlgorithm();
    final String password = context.getProperty(PASSWORD).getValue();
    final KeyDerivationFunction kdf = KeyDerivationFunction.valueOf(context.getProperty(KEY_DERIVATION_FUNCTION).getValue());
    final boolean encrypt = context.getProperty(MODE).getValue().equalsIgnoreCase(ENCRYPT_MODE);
    Encryptor encryptor;
    StreamCallback callback;
    try {
        if (isPGPAlgorithm(algorithm)) {
            final String filename = flowFile.getAttribute(CoreAttributes.FILENAME.key());
            final String publicKeyring = context.getProperty(PUBLIC_KEYRING).getValue();
            final String privateKeyring = context.getProperty(PRIVATE_KEYRING).getValue();
            if (encrypt && publicKeyring != null) {
                final String publicUserId = context.getProperty(PUBLIC_KEY_USERID).getValue();
                encryptor = new OpenPGPKeyBasedEncryptor(algorithm, providerName, publicKeyring, publicUserId, null, filename);
            } else if (!encrypt && privateKeyring != null) {
                final char[] keyringPassphrase = context.getProperty(PRIVATE_KEYRING_PASSPHRASE).evaluateAttributeExpressions().getValue().toCharArray();
                encryptor = new OpenPGPKeyBasedEncryptor(algorithm, providerName, privateKeyring, null, keyringPassphrase, filename);
            } else {
                final char[] passphrase = Normalizer.normalize(password, Normalizer.Form.NFC).toCharArray();
                encryptor = new OpenPGPPasswordBasedEncryptor(algorithm, providerName, passphrase, filename);
            }
        } else if (kdf.equals(KeyDerivationFunction.NONE)) {
            // Raw key
            final String keyHex = context.getProperty(RAW_KEY_HEX).getValue();
            encryptor = new KeyedEncryptor(encryptionMethod, Hex.decodeHex(keyHex.toCharArray()));
        } else {
            // PBE
            final char[] passphrase = Normalizer.normalize(password, Normalizer.Form.NFC).toCharArray();
            encryptor = new PasswordBasedEncryptor(encryptionMethod, passphrase, kdf);
        }
        if (encrypt) {
            callback = encryptor.getEncryptionCallback();
        } else {
            callback = encryptor.getDecryptionCallback();
        }
    } catch (final Exception e) {
        logger.error("Failed to initialize {}cryption algorithm because - ", new Object[] { encrypt ? "en" : "de", e });
        session.rollback();
        context.yield();
        return;
    }
    try {
        final StopWatch stopWatch = new StopWatch(true);
        flowFile = session.write(flowFile, callback);
        logger.info("successfully {}crypted {}", new Object[] { encrypt ? "en" : "de", flowFile });
        session.getProvenanceReporter().modifyContent(flowFile, stopWatch.getElapsed(TimeUnit.MILLISECONDS));
        session.transfer(flowFile, REL_SUCCESS);
    } catch (final ProcessException e) {
        logger.error("Cannot {}crypt {} - ", new Object[] { encrypt ? "en" : "de", flowFile, e });
        session.transfer(flowFile, REL_FAILURE);
    }
}
Also used : FlowFile(org.apache.nifi.flowfile.FlowFile) KeyedEncryptor(org.apache.nifi.security.util.crypto.KeyedEncryptor) PasswordBasedEncryptor(org.apache.nifi.security.util.crypto.PasswordBasedEncryptor) KeyedEncryptor(org.apache.nifi.security.util.crypto.KeyedEncryptor) OpenPGPPasswordBasedEncryptor(org.apache.nifi.security.util.crypto.OpenPGPPasswordBasedEncryptor) OpenPGPKeyBasedEncryptor(org.apache.nifi.security.util.crypto.OpenPGPKeyBasedEncryptor) EncryptionMethod(org.apache.nifi.security.util.EncryptionMethod) ComponentLog(org.apache.nifi.logging.ComponentLog) OpenPGPKeyBasedEncryptor(org.apache.nifi.security.util.crypto.OpenPGPKeyBasedEncryptor) StreamCallback(org.apache.nifi.processor.io.StreamCallback) ProcessException(org.apache.nifi.processor.exception.ProcessException) DecoderException(org.apache.commons.codec.DecoderException) StopWatch(org.apache.nifi.util.StopWatch) KeyDerivationFunction(org.apache.nifi.security.util.KeyDerivationFunction) ProcessException(org.apache.nifi.processor.exception.ProcessException) OpenPGPPasswordBasedEncryptor(org.apache.nifi.security.util.crypto.OpenPGPPasswordBasedEncryptor) PasswordBasedEncryptor(org.apache.nifi.security.util.crypto.PasswordBasedEncryptor) OpenPGPPasswordBasedEncryptor(org.apache.nifi.security.util.crypto.OpenPGPPasswordBasedEncryptor)

Example 2 with KeyDerivationFunction

use of org.apache.nifi.security.util.KeyDerivationFunction in project nifi by apache.

the class EncryptContent method getKDFsForKeyedCipher.

private List<String> getKDFsForKeyedCipher() {
    List<String> kdfsForKeyedCipher = new ArrayList<>();
    kdfsForKeyedCipher.add(KeyDerivationFunction.NONE.name());
    for (KeyDerivationFunction k : KeyDerivationFunction.values()) {
        if (k.isStrongKDF()) {
            kdfsForKeyedCipher.add(k.name());
        }
    }
    return kdfsForKeyedCipher;
}
Also used : KeyDerivationFunction(org.apache.nifi.security.util.KeyDerivationFunction) ArrayList(java.util.ArrayList)

Example 3 with KeyDerivationFunction

use of org.apache.nifi.security.util.KeyDerivationFunction in project nifi by apache.

the class EncryptContent method customValidate.

@Override
protected Collection<ValidationResult> customValidate(final ValidationContext context) {
    final List<ValidationResult> validationResults = new ArrayList<>(super.customValidate(context));
    final String methodValue = context.getProperty(ENCRYPTION_ALGORITHM).getValue();
    final EncryptionMethod encryptionMethod = EncryptionMethod.valueOf(methodValue);
    final String algorithm = encryptionMethod.getAlgorithm();
    final String password = context.getProperty(PASSWORD).getValue();
    final KeyDerivationFunction kdf = KeyDerivationFunction.valueOf(context.getProperty(KEY_DERIVATION_FUNCTION).getValue());
    final String keyHex = context.getProperty(RAW_KEY_HEX).getValue();
    if (isPGPAlgorithm(algorithm)) {
        final boolean encrypt = context.getProperty(MODE).getValue().equalsIgnoreCase(ENCRYPT_MODE);
        final String publicKeyring = context.getProperty(PUBLIC_KEYRING).getValue();
        final String publicUserId = context.getProperty(PUBLIC_KEY_USERID).getValue();
        final String privateKeyring = context.getProperty(PRIVATE_KEYRING).getValue();
        final String privateKeyringPassphrase = context.getProperty(PRIVATE_KEYRING_PASSPHRASE).evaluateAttributeExpressions().getValue();
        validationResults.addAll(validatePGP(encryptionMethod, password, encrypt, publicKeyring, publicUserId, privateKeyring, privateKeyringPassphrase));
    } else {
        // Not PGP
        if (encryptionMethod.isKeyedCipher()) {
            // Raw key
            validationResults.addAll(validateKeyed(encryptionMethod, kdf, keyHex));
        } else {
            // PBE
            boolean allowWeakCrypto = context.getProperty(ALLOW_WEAK_CRYPTO).getValue().equalsIgnoreCase(WEAK_CRYPTO_ALLOWED_NAME);
            validationResults.addAll(validatePBE(encryptionMethod, kdf, password, allowWeakCrypto));
        }
    }
    return validationResults;
}
Also used : KeyDerivationFunction(org.apache.nifi.security.util.KeyDerivationFunction) ArrayList(java.util.ArrayList) EncryptionMethod(org.apache.nifi.security.util.EncryptionMethod) ValidationResult(org.apache.nifi.components.ValidationResult)

Example 4 with KeyDerivationFunction

use of org.apache.nifi.security.util.KeyDerivationFunction in project nifi by apache.

the class EncryptContent method buildKeyDerivationFunctionAllowableValues.

private static AllowableValue[] buildKeyDerivationFunctionAllowableValues() {
    final KeyDerivationFunction[] keyDerivationFunctions = KeyDerivationFunction.values();
    List<AllowableValue> allowableValues = new ArrayList<>(keyDerivationFunctions.length);
    for (KeyDerivationFunction kdf : keyDerivationFunctions) {
        allowableValues.add(new AllowableValue(kdf.name(), kdf.getName(), kdf.getDescription()));
    }
    return allowableValues.toArray(new AllowableValue[0]);
}
Also used : KeyDerivationFunction(org.apache.nifi.security.util.KeyDerivationFunction) AllowableValue(org.apache.nifi.components.AllowableValue) ArrayList(java.util.ArrayList)

Example 5 with KeyDerivationFunction

use of org.apache.nifi.security.util.KeyDerivationFunction in project nifi by apache.

the class TestEncryptContent method testShouldDecryptOpenSSLRawSalted.

@Test
public void testShouldDecryptOpenSSLRawSalted() throws IOException {
    // Arrange
    Assume.assumeTrue("Test is being skipped due to this JVM lacking JCE Unlimited Strength Jurisdiction Policy file.", PasswordBasedEncryptor.supportsUnlimitedStrength());
    final TestRunner testRunner = TestRunners.newTestRunner(new EncryptContent());
    final String password = "thisIsABadPassword";
    final EncryptionMethod method = EncryptionMethod.MD5_256AES;
    final KeyDerivationFunction kdf = KeyDerivationFunction.OPENSSL_EVP_BYTES_TO_KEY;
    testRunner.setProperty(EncryptContent.PASSWORD, password);
    testRunner.setProperty(EncryptContent.KEY_DERIVATION_FUNCTION, kdf.name());
    testRunner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, method.name());
    testRunner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);
    // Act
    testRunner.enqueue(Paths.get("src/test/resources/TestEncryptContent/salted_raw.enc"));
    testRunner.clearTransferState();
    testRunner.run();
    // Assert
    testRunner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);
    testRunner.assertQueueEmpty();
    MockFlowFile flowFile = testRunner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
    logger.info("Decrypted contents (hex): {}", Hex.encodeHexString(flowFile.toByteArray()));
    logger.info("Decrypted contents: {}", new String(flowFile.toByteArray(), "UTF-8"));
    // Assert
    flowFile.assertContentEquals(new File("src/test/resources/TestEncryptContent/plain.txt"));
}
Also used : MockFlowFile(org.apache.nifi.util.MockFlowFile) KeyDerivationFunction(org.apache.nifi.security.util.KeyDerivationFunction) TestRunner(org.apache.nifi.util.TestRunner) EncryptionMethod(org.apache.nifi.security.util.EncryptionMethod) File(java.io.File) MockFlowFile(org.apache.nifi.util.MockFlowFile) Test(org.junit.Test)

Aggregations

KeyDerivationFunction (org.apache.nifi.security.util.KeyDerivationFunction)6 EncryptionMethod (org.apache.nifi.security.util.EncryptionMethod)4 ArrayList (java.util.ArrayList)3 File (java.io.File)2 MockFlowFile (org.apache.nifi.util.MockFlowFile)2 TestRunner (org.apache.nifi.util.TestRunner)2 Test (org.junit.Test)2 DecoderException (org.apache.commons.codec.DecoderException)1 AllowableValue (org.apache.nifi.components.AllowableValue)1 ValidationResult (org.apache.nifi.components.ValidationResult)1 FlowFile (org.apache.nifi.flowfile.FlowFile)1 ComponentLog (org.apache.nifi.logging.ComponentLog)1 ProcessException (org.apache.nifi.processor.exception.ProcessException)1 StreamCallback (org.apache.nifi.processor.io.StreamCallback)1 KeyedEncryptor (org.apache.nifi.security.util.crypto.KeyedEncryptor)1 OpenPGPKeyBasedEncryptor (org.apache.nifi.security.util.crypto.OpenPGPKeyBasedEncryptor)1 OpenPGPPasswordBasedEncryptor (org.apache.nifi.security.util.crypto.OpenPGPPasswordBasedEncryptor)1 PasswordBasedEncryptor (org.apache.nifi.security.util.crypto.PasswordBasedEncryptor)1 StopWatch (org.apache.nifi.util.StopWatch)1