Spring Download - JSON Data Encryption

In our application, we must encrypt / decrypt the Json property values ​​(and not the property name) for each request and response. Example,
{"userName":"encrypted value", "email":"encrypted value"}

We are using Sprint 1.3 download, and we are using @RequestBody and @ResponseBody annotations to associate the json request with the object and serialize the response object as JSON.

We do not want to call the encryption / decryption method in each of our controller methods. Is there any way to instruct sprint to decrypt json values ​​before binding to the request object? Similarly, to encrypt the response object field values ​​before converting them to json? Or can Jackson tuning help us?

Thanks!

+8
json spring jackson spring-boot
source share
1 answer

You can write your own HTTP message converter. Since you are using spring boot, it will be pretty simple: just add your custom converter from AbstractHttpMessageConverter and mark the class with @Component annotation.

From spring docs :

You can add additional converters by simply adding beans of this type to the spring boot context. If the added bean is a type that would be enabled by default anyway (for example, MappingJackson2HttpMessageConverter for JSON conversions), then it will replace the default value.

And here is a simple example:

 @Component public class Converter extends AbstractHttpMessageConverter<Object> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); @Inject private ObjectMapper objectMapper; public Converter(){ super(MediaType.APPLICATION_JSON_UTF8, new MediaType("application", "*+json", DEFAULT_CHARSET)); } @Override protected boolean supports(Class<?> clazz) { return true; } @Override protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { return objectMapper.readValue(decrypt(inputMessage.getBody()), clazz); } @Override protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { outputMessage.getBody().write(encrypt(objectMapper.writeValueAsBytes(o))); } private InputStream decrypt(InputStream inputStream){ // do your decryption here return inputStream; } private byte[] encrypt(byte[] bytesToEncrypt){ // do your encryption here return bytesToEncrypt; } } 
+8
source share

All Articles