· 9 years ago · Oct 27, 2016, 11:28 PM
1import javax.crypto.Cipher
2import javax.crypto.SecretKey
3import javax.crypto.spec.IvParameterSpec
4import javax.crypto.spec.SecretKeySpec
5import java.nio.charset.StandardCharsets
6
7FlowFile flowFile = session.get()
8
9try {
10 // Get the raw values of the attributes
11 String normalAttribute = flowFile.getAttribute('Normal Attribute')
12 String sensitiveAttribute = flowFile.getAttribute('Sensitive Attribute')
13
14 // Instantiate an encryption cipher
15 // 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.
16 String keyHex = "0123456789ABCDEFFEDCBA9876543210" * 2
17 keyHex = "0" * 32
18 SecretKey key = new SecretKeySpec(keyHex.getBytes(StandardCharsets.UTF_8), "AES")
19 IvParameterSpec iv = new IvParameterSpec(keyHex[0..<16].getBytes(StandardCharsets.UTF_8))
20
21 Cipher aesGcmEncCipher = Cipher.getInstance("AES/GCM/NoPadding", "BC")
22 aesGcmEncCipher.init(Cipher.ENCRYPT_MODE, key, iv)
23
24 String encryptedNormalAttribute = Base64.encoder.encodeToString(aesGcmEncCipher.doFinal(normalAttribute.bytes))
25 String encryptedSensitiveAttribute = Base64.encoder.encodeToString(aesGcmEncCipher.doFinal(sensitiveAttribute.bytes))
26
27 // Add a new attribute with the encrypted normal attribute
28 flowFile = session.putAttribute(flowFile, 'Normal Attribute (encrypted)', encryptedNormalAttribute)
29
30 // Replace the sensitive attribute inline with the cipher text
31 flowFile = session.putAttribute(flowFile, 'Sensitive Attribute', encryptedSensitiveAttribute)
32 session.transfer(flowFile, REL_SUCCESS)
33} catch (Exception e) {
34 log.error("There was an error encrypting the attributes: ${e.getMessage()}")
35 session.transfer(flowFile, REL_FAILURE)
36}