Nifi 加密 json

Nifi Encrypt json

我想使用 nifi 来加密 json 中的属性,而不是密钥,因为我想将数据上传到 mongodb 服务器。有没有办法做到这一点?对于该项目,我使用推特数据作为概念证明。到目前为止,我已经使用 EvaluateJsonPath 处理器仅提取推文的文本,并且我可以加密该文本,但是生成的 json 不再具有密钥。 Nifi 可以重新创建一个 json 将密钥附加到我提取的这个属性吗?有更好的方法吗?

遗憾的是,现有的 Apache NiFi 处理器无法很好地支持此工作流。您可能会设计一个工作流,将 JSON 内容拆分为属性,将每个属性拆分为单个流文件的内容,加密该内容,合并流文件,然后通过 UpdateAttribute

我有 created a Jira for a new NiFi processor to make this much simpler. My recommendation until such time as that is available is to use the ExecuteScript processor to achieve this. I have provided a template 示例,您可以将其直接导入您的 NiFi 实例并连接到您的流程。下面提供了 ExecuteScript 处理器的主体(您可以看到我如何初始化 AES/GCM 密码,并将算法、密钥和 IV 更改为您想要的值)。

import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
import java.nio.charset.StandardCharsets

FlowFile flowFile = session.get()

if (!flowFile) {
    return
}

try {
    // Get the raw values of the attributes
    String normalAttribute = flowFile.getAttribute('Normal Attribute')
    String sensitiveAttribute = flowFile.getAttribute('Sensitive Attribute')

    // Instantiate an encryption cipher
    // Lots of additional code could go here to generate a random key, derive a key from a password, read from a file or keyring, etc.
    String keyHex = "0123456789ABCDEFFEDCBA9876543210" // * 2 for 256-bit encryption
    SecretKey key = new SecretKeySpec(keyHex.getBytes(StandardCharsets.UTF_8), "AES")
    IvParameterSpec iv = new IvParameterSpec(keyHex[0..<16].getBytes(StandardCharsets.UTF_8))

    Cipher aesGcmEncCipher = Cipher.getInstance("AES/GCM/NoPadding", "BC")
    aesGcmEncCipher.init(Cipher.ENCRYPT_MODE, key, iv)

    String encryptedNormalAttribute = Base64.encoder.encodeToString(aesGcmEncCipher.doFinal(normalAttribute.bytes))
    String encryptedSensitiveAttribute = Base64.encoder.encodeToString(aesGcmEncCipher.doFinal(sensitiveAttribute.bytes))

    // Add a new attribute with the encrypted normal attribute
    flowFile = session.putAttribute(flowFile, 'Normal Attribute (encrypted)', encryptedNormalAttribute)

    // Replace the sensitive attribute inline with the cipher text
    flowFile = session.putAttribute(flowFile, 'Sensitive Attribute', encryptedSensitiveAttribute)
    session.transfer(flowFile, REL_SUCCESS)
} catch (Exception e) {
    log.error("There was an error encrypting the attributes: ${e.getMessage()}")
    session.transfer(flowFile, REL_FAILURE)
}