Spring decryption of JSON requests

Source: Internet
Author: User
Tags base64 decrypt

Processing JSON requests in spring typically uses @requestbody and @responsebody annotations to decrypt and filter strings for JSON requests. Spring provides Requestbodyadvice and Responsebodyadvice two interfaces
Specific use
1. Decryption:

Import Com.hive.util.aesoperator;import Org.apache.commons.io.ioutils;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.springframework.core.methodparameter;import Org.springframework.http.httpheaders;import Org.springframework.http.httpinputmessage;import Org.springframework.http.converter.httpmessageconverter;import Org.springframework.web.bind.annotation.controlleradvice;import Org.springframework.web.servlet.mvc.method.annotation.requestbodyadvice;import Java.io.IOException;import Java.io.inputstream;import Java.lang.reflect.Type;/** * Request Data Decryption */@ControllerAdvice (basepackages ="Com.hive")PublicClassMyrequestbodyadviceImplementsRequestbodyadvice {PrivateFinalstatic Logger Logger = Loggerfactory.getlogger (Myresponsebodyadvice.class); @OverridePublic Boolean supports (Methodparameter methodparameter, Type TargetType,class<?ExtendsHttpmessageconverter<?>>Convertertype) {ReturnTrue } @Overridepublic object Handleemptybody (object body, Httpinputmessage inputmessage, methodparameter parameter, Type TargetType,class<?ExtendsHttpmessageconverter<?>>Convertertype) {return body; } @OverridePublic Httpinputmessage Beforebodyread (httpinputmessage inputmessage, methodparameter parameter, Type TargetType,class<?ExtendsHttpmessageconverter<?>>Convertertype)ThrowsIOException {try {ReturnNew Myhttpinputmessage (inputmessage); }catch (Exception e) {e.printstacktrace ();return inputmessage; }} @Overridepublic object Afterbodyread (object body, Httpinputmessage inputmessage, methodparameter parameter, Type TargetType,class<?ExtendsHttpmessageconverter<?>>Convertertype) {return body; }class myhttpinputmessage  Implements httpinputmessage {private httpheaders headers; private inputstream body; public myhttpinputmessage (Httpinputmessage inputmessage) throws exception {this.headers = Inputmessage.getheaders (); this.body = IOUtils.toInputStream ( Aesoperator.getinstance (). Decrypt (Ioutils.tostring (Inputmessage.getbody (),  "UTF-8"),  "UTF-8"); } @Override public InputStream getbody () throws IOException { return body; } @Override public httpheaders getheaders () {return Headers;}}} 

2. Encryption:

Package Com.hive.core.json;Import com.fasterxml.jackson.core.JsonProcessingException;Import Com.fasterxml.jackson.databind.ObjectMapper;Import Com.hive.util.AESOperator;Import Org.slf4j.Logger;Import Org.slf4j.LoggerFactory;Import Org.springframework.core.MethodParameter;Import Org.springframework.http.MediaType;Import Org.springframework.http.server.ServerHttpRequest;Import Org.springframework.http.server.ServerHttpResponse;Import Org.springframework.web.bind.annotation.ControllerAdvice;Import Org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;/** * Return Data encryption */@ControllerAdvice (basepackages ="Com.hive")PublicClassMyresponsebodyadviceImplementsResponsebodyadvice {PrivateFinalstatic Logger Logger = Loggerfactory.getlogger (Myresponsebodyadvice.class);PrivateFinalstatic String KEY ="[Email protected]* ( -8l";@OverridePublicBooleanSupports (Methodparameter returntype, Class convertertype) {ReturnTrue }@OverridePublic ObjectBeforebodywrite (Object body, methodparameter returntype, mediatype Selectedcontenttype, Class Selectedconvertertype, ServerHTTPRequest request, serverhttpresponse response) {Boolean encode =Falseif (Returntype.getmethod (). Isannotationpresent (Serializedfield.class)) {//Get the inclusion and removal fields of the annotation configuration Serializedfield Serializedfield = returntype.getmethodannotation (Serializedfield.class); //Whether encryption encode = Serializedfield.encode ();} if (encode) {Logger.info ("to Method:" + Returntype.getmethod (). GetName () + "Return data for Encryption"); Objectmapper objectmapper = new Objectmapper (); try {String result = Objectmapper.writerwithdefaultprettyprinter (). writevalueasstring (body); return Aesoperator.getinstance (). Encrypt (result);} catch (Jsonprocessingexception e) {e.printstacktrace ();} catch (Exception e) {e.printstacktrace ();}} return body;}}          

Annotation class:

package Com.hive.core.json; import org.springframework.web.bind.annotation.Mapping; import java.lang.annotation.*;  @Target ({elementtype.method, elementtype.type}) @ Retention (retentionpolicy.runtime)  @Documented @ Mappingpublic @interface serializedfield {/** * encrypted * @return */ boolean encode () default true;} 
} /code>


The default is true, I use false on this side. You can also define a string that needs to be filtered in the annotation class

AES Encryption Class

Package com.hive.util;Import Sun.misc.BASE64Decoder;Import Sun.misc.BASE64Encoder;Import Javax.crypto.Cipher;Import Javax.crypto.spec.IvParameterSpec;Import Javax.crypto.spec.SecretKeySpec;/** * AES CBC Encryption */PublicClassAesoperator {/* * Encryption key can be used in 26 letters and numbers here to use AES-128-CBC encryption mode, key needs to be 16 bits. */Private String KEY ="[Email protected]* ( -8l";Private String VECTOR ="! Wfnzfu_{h%m (s|a ";PrivateStatic Aesoperator instance =NullPrivateAesoperator () {}PublicStatic AesoperatorGetInstance () {return nested.instance; }The internal static class will only be loaded once, so the implementation is thread-safe!Static Class Nested {PrivateStatic Aesoperator instance =New Aesoperator (); }/** * Encryption * *@param content *@return *@throws Exception * *Public StringEncrypt (String content)Throws Exception {Return Encrypt (content, KEY, VECTOR); }/** * Encryption * *@param content *@return *@throws Exception * *Public StringEncrypt (String content,string key)Throws Exception {Return Encrypt (content, key, VECTOR); }/** * Encryption * *@param content *@param key *@param vector *@return *@throws Exception * *Public StringEncrypt (string content, string key, String vector)Throws Exception {if (key = =NULL) {ReturnNull }if (Key.length ()! =16) {ReturnNull } Secretkeyspec Skeyspec =New Secretkeyspec (Key.getbytes ("UTF-8"),"AES"); Ivparameterspec IV =New Ivparameterspec (Vector.getbytes ());With CBC mode, a vector IV is required to increase the strength of the cryptographic algorithm Cipher Cipher = cipher.getinstance ("Aes/cbc/pkcs5padding"); Cipher.init (Cipher.encrypt_mode, Skeyspec, iv);Byte[] encrypted = cipher.dofinal (Content.getbytes ("UTF-8"));ReturnNew Base64encoder (). Encode (encrypted);Transcoding is done here using BASE64. }/** * Decryption * *@param content *@return *@throws Exception * *Public StringDecrypt (String content)Throws Exception {Return decrypt (content, KEY, VECTOR); }/** * Decryption * *@param content *@return *@throws Exception * *Public StringDecrypt (String content,string key)Throws Exception {Return decrypt (content, key, VECTOR); }/** * Decryption * *@param content *@param key *@param vector *@return *@throws Exception * *Public StringDecrypt (string content, string key, String vector)Throws Exception {try {if (key = =NULL) {ReturnNull }if (Key.length ()! =16) {ReturnNull } Secretkeyspec Skeyspec =New Secretkeyspec (Key.getbytes ("UTF-8"),"AES"); Ivparameterspec IV =New Ivparameterspec (Vector.getbytes ()); Cipher Cipher = cipher.getinstance ("Aes/cbc/pkcs5padding"); Cipher.init (Cipher.decrypt_mode, Skeyspec, iv);byte[] Encrypted1 =New Base64decoder (). Decodebuffer (content);First decrypt with Base64.byte[] Original = cipher.dofinal (encrypted1); String originalstring =New String (Original,"UTF-8");return originalstring; }catch (Exception ex) {ReturnNull } }PublicStaticvoidMain (string[] args)Throws Exception {//need to encrypt strings string CSRC =  "I love You"; //encryption long Lstart = System.currenttimemillis (); String enstring = Aesoperator.getinstance (). Encrypt (Csrc, "[Email protected]* ( -8L") ; System.out.println ( "after the encrypted string is:" + enstring); long lusetime = System.currenttimemillis ()-Lstart; System.out.println ( "Encryption Time:" + lusetime +  "milliseconds"); //Decryption Lstart = System.currenttimemillis (); String destring = Aesoperator.getinstance (). Decrypt (enstring); System.out.println ( "The decrypted string is:" + destring); lusetime = System.currenttimemillis ()-Lstart; System.out.println ( "decryption time:" + lusetime +  "milliseconds");}}   

Spring decrypts JSON requests

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.