A Jackson module to support JSON encryption and decryption operations. Encryption is via AES. Key generation is password based.
Keyword: Jackson, JSON, AES, PKCS5, Encryption, Salt, Initialization Vector, IV, Java
Based on an idea from meltmedia
If you find this project useful, you may want to Buy me a Coffee! ☕ Thanks 👍
Windows
gradlew clean build test
Linux
./gradlew clean build test
These examples are demonstrated in the CryptoDemo
unit test class
Add the crypto module to your project. Common use case with a cipher of AES/CBC/PKCS5Padding and a key factory algorithm of PBKDF2WithHmacSHA512
Just supply a password.
ObjectMapper objectMapper = EncryptionService.getInstance("Password1");
Similar to Option 1, but you already have a ObjectMapper
ObjectMapper objectMapper = ...
EncryptionService encryptionService =
new EncryptionService(objectMapper, new PasswordCryptoContext("Password1");
objectMapper.registerModule(new CryptoModule().addEncryptionService(encryptionService));
Where you just need full control.
// get an object mapper
ObjectMapper objectMapper = new ObjectMapper();
// set up a custom crypto context - Defines the interface to the crypto algorithms used
ICryptoContext cryptoContext = new PasswordCryptoContext("Password");
// The encryption service holds functionality to map clear to / from encrypted JSON
EncryptionService encryptionService = new EncryptionService(objectMapper, cryptoContext);
// Create a Jackson module and tell it about the encryption service
CryptoModule cryptoModule = new CryptoModule().addEncryptionService(encryptionService);
// Tell Jackson about the new module
objectMapper.registerModule(cryptoModule);
Any field that is required to be encrypted has to be marked as such. This can be done by either annotating the getter() or by annotating the field definition.
This ...
private String critical;
...
@JsonProperty
@Encrypt
public String getCritical() {
return this.critical;
}
... or ...
@JsonProperty
@Encrypt
private String critical;
{
"critical":{
"salt":"IRqsz99no75sx9SCGrzOSEdoMVw=",
"iv":"bfKvxBhq7X5su9VtvDdOGQ==",
"value":"pXWsFPzCnmPieitbGfkvofeQE3fj0Kb4mSP7e28+Jc0="
}
}
The project includes a Jenkins file to control a pipeline build.
<dependency>
<groupId>com.codingrodent</groupId>
<artifactId>jackson-json-crypto</artifactId>
<version>2.2.0</version>
</dependency>
compile group: 'com.codingrodent', name: 'jackson-json-crypto', version: '2.2.0'