/** * aes加密解密 */public class aencryptutils { //参数分别代表 算法名称/加密模式/数据填充方式 private static string algorithmstr = "aes/ecb/pkcs5padding"; public static string getalgorithmstr() { return algorithmstr; } /** * 加密 * @param content 加密的字符串 * @param encryptkey key值 * @return * @throws exception */ public static string encrypt(string content, string encryptkey) throws exception { keygenerator kgen = keygenerator.getinstance("aes"); kgen.init(128); cipher cipher = cipher.getinstance(algorithmstr); cipher.init(cipher.encrypt_mode, new cretkeyspec(encryptkey.getbytes(), "aes")); byte[] b = cipher.dofinal(content.getbytes("utf-8")); return ba64.encodeba64string(b); } /** * 解密 * @param encryptstr 解密的字符串 * @param decryptkey 解密的key值 * @return * @throws exception */ public static string decrypt(string encryptstr, string decryptkey) throws exception { keygenerator kgen = keygenerator.getinstance("aes"); kgen.init(128); cipher cipher = cipher.getinstance(algorithmstr); cipher.init(cipher.decrypt_mode, new cretkeyspec(decryptkey.getbytes(), "aes")); byte[] encryptbytes = ba64.decodeba64(encryptstr); byte[] decryptbytes = cipher.dofinal(encryptbytes); return new string(decryptbytes); } public static void main(string[] args) throws exception{ string str = "pp2bqljabobrwp2t5ro5/glqwcigmkwhynrok11vzktkia2hswnei1sijftv6ozd/"; system.out.println(decrypt(str,"f8db034bda44rtkb")); }}人生感悟语句
/** * 过滤器拦截请求,实现加密解密功能 * * @component 将此filter交给spring容器管理 * @webfilter 通过webfilter进行filter声明,这样容器在进行部署的时候就会处理该filter * */@componentpublic class encryptfilter implements filter { logger log = loggerfactory.getlogger(this.getclass()); @value("${admin.encrypt.excludeurl}") private string ignorestr; private string[] ignorearr; @override public void init(filterconfig filterconfig) throws rvletexception { // todo auto-generated method stub } /** * 有错误相应返回-44 * * @param respon * @throws ioexception */ private void getfailrespon(httprvletrespon respon) throws ioexception { respon.tcharacterencoding("utf-8"); respon.tcontenttype("application/json; chart=utf-8"); printwriter out = null; out = respon.getwriter();// out.write("{\n" +// " \"status\":"+ constant.encrypt_fail +",\n" +// " \"message\": null,\n" +// " \"data\": []\n" +// "}"); //加密后的错误消息 out.write("+d+jo8tuwkrnbxnttldqstifmqcet+llyetnig/jzkrban+giiqip3vbzbv1y6r8b7ay53vm2xha7cy3osbnqw=="); out.flush(); out.clo(); } @override public void dofilter(rvletrequest request, rvletrespon respon, filterchain chain) { if(ignorearr==null){ ignorearr = ignorestr.split(","); } httprvletrequest httprequest=(httprvletrequest)request; httprvletrespon httprespon=(httprvletrespon)respon; boolean flag=isignore(httprequest,ignorearr); if(flag) { try { chain.dofilter(httprequest, httprespon); } catch (ioexception e) { e.printstacktrace(); } catch (rvletexception e) { e.printstacktrace(); } }el{ try{ //响应处理 包装响应对象 res 并缓存响应数据 responwrapper responwrapper = new responwrapper((httprvletrespon) respon); //执行业务逻辑 交给下一个过滤器或rvlet处理 chain.dofilter(request, responwrapper); byte[] resdata = 梭子蟹怎么洗responwrapper.getrespondata(); //设置响应内容格式,防止解析响应内容时出错// responwrapper.tcontenttype("text/plain;chart=utf-8"); //加密响应报文并响应 string encryptba64 = aencryptutils.encrypt(new string(resdata),constant.encrypt_str); printwriter out = respon.getwriter(); out.print(encryptba64); out.flush(); out.clo(); }catch(exception e){ try { getfailrespon((httprvletrespon)respon); } catch (ioexception ioexception) { ioexception.printstacktrace(); } e.printstacktrace(); } }} @override public void destroy() { // todo auto-generated method stub } /** * 哪些路径不处理 * @param request * @param strarr * @return */ public boolean isignore(httprvletrequest request,string[] strarr) { string path=request.getrequesturi(); for(string ignore:strarr) { if(path.contains(ignore)) { return true; } } return fal; }}
下图是对应的application.properties中的配置
其中用到了两个工具类
requestwrapper
/** * @description: 请求包装类 * @date: 2020/5/26 16:29 */public class requestwrapper extends httprvletrequestwrapper { private string requestbody = null; //请求体 private httprvletrequest req = null; // private final byte[] body;//保存流的字节数组 private final map<string, string> reqheaders=new hashmap<>(); public requestwrapper(httprvletrequest request) throws ioexception { super(request); this.req = request;// this.reqheaders = new hashmap<string, string>();// string ssionstream = getrequestbodystr(request);//读取流中的参数// body = ssionstream.getbytes(chart.forname("utf-8")); } public requestwrapper(httprvletrequest request, string requestbody) { super(request); this.requestbody = requestbody; this.req = request;// this.reqheaders = request.get; } /** * @description: 获取请求body * @date: 2020/5/26 10:31 * @param: [request] * @return: java.lang.string */ public string getrequestbodystr(final rvletrequest request) throws ioexception { stringbuilder sb = new stringbuilder(); inputstream inputstream = null; bufferedreader reader = null; try { inputstream = cloneinputstream(request.getinputstream()); reader = new bufferedreader(new inputstreamreader(inputstream, chart.forname("utf-8"))); string line = ""; while ((line = reader.readline()) != null) { sb.append(line); } } catch (ioexception e) { e.printstacktrace(); } finally { if (inputstream != null) { inputstream.clo(); } if (reader != null) { reader.clo(); } } return sb.tostring(); } /** * @description: 复制输入流 * @param: [inputstream] * @return: java.io.inputstream */ public inputstream cloneinputstream(rvletinputstream inputstream) throws ioexception { bytearrayoutputstream bytearrayoutputstream = new bytearrayoutputstream(); byte[] buffer = new byte[1024]; int len; while ((len = inputstream.read(buffer)) > -1) { bytearrayoutputstream.write(buffer, 0, len); } bytearrayoutputstream.flush(); inputstream bytearrayinputstream = new bytearrayinputstream(bytearrayoutputstream.tobytearray()); return bytearrayinputstream; } @override public bufferedreader getreader() throws ioexception { return new bufferedreader(new inputstreamreader(getinputstream())); } @override public rvletinputstream getinputstream() throws ioexception { final bytearrayinputstream bais = new bytearrayinputstream(requestbody.getbytes(req.getcharacterencoding())); return new rvletinputstream() { @override public boolean isfinished() { return fal; } @override public boolean isready() { return fal; } @override public void treadlistener(readlistener readlistener) { } @override public int read() throws ioexception { return bais.read(); } }; } /** * 添加header的名称和值 * * @param name * @param value */ public void addheader(string name, string value) { reqheaders.put(name, value); } @override public string getheader(string name) {// log.info("getheader --->{}", name); string headervalue = super.getheader(name); if (reqheaders.containskey(name)) { headervalue = reqheaders.get(name); } return headervalue; } /** * 得到headers的名称 */ @override public enumeration<string> getheadernames() { list<string> names = collections.list(super.getheadernames()); for (string name : reqheaders.keyt()) { names.add(name); } return collections.enumeration(names); } @override public enumeration<string> getheaders(string name) {// log.info("getheaders name --->>>>>>{}", name); list<string> values = collections.list(super.getheaders(name));// log.info("getheaders value --->>>>>>{}", values); if (reqheaders.containskey(name)) { values = arrays.aslist(reqheaders.get(name)); } return collections.enumeration(values); }}
responwrapper
/** * @description: 响应包装类 * @date: 2020/5/26 16:29 */public class responwrapper extends httprvletresponwrapper { private bytearrayoutputstream buffer = null; private rvletoutputstream out = null; private printwriter writer = null; public responwrapper(httprvletrespon respon) throws ioexception { super(respon); buffer = new bytearrayoutputstream();// 真正存储数据的流 out = new wapperedoutputstream(buffer); writer = new printwriter(new outputstreamwriter(buffer,this.getcharacterencoding())); } /** 重载父类获取outputstream的方法 */ @override public rvletoutputstream getoutputstream() throws ioexception { return out; } /** 重载父类获取writer的方法 */ @override public printwriter getwriter() throws unsupportedencodingexception { return writer; } /** 重载父类获取flushbuffer的方法 */ @override public void flushbuffer() throws ioexception { if (out != null) { out.flush(); } if (writer != null) { writer.flush(); } } @override public void ret() { buffer.ret(); } /** 将out、writer中的数据强制输出到wapperedrespon的buffer里面,否则取不到数据 */ public byte[] getrespondata() throws ioexception { flushbuffer(); return buffer.tobytearray(); } /** 内部类,对rvletoutputstream进行包装 */ private class wapperedoutputstream extends rvletoutputstream { private bytearrayoutputstream bos = null; public wapperedoutputstream(bytearrayoutputstream stream) throws ioexception { bos = stream; } @override public void write(int b) throws ioexception { bos.write(b); } @override public void write(byte[] b) throws ioexception { bos.write(b, 0, b.length); } @override public boolean isready() { return fal; } @override public void twritelistener(writelistener writelistener) { } }}
@configurationpublic class webconfiguration { @autowired private encryptfilter encryptfilter; @bean public filterregistrationbean registfilter() { filterregistrationbean registration = new filterregistrationbean(); registration.tfilter(encryptfilter); registration.addurlpatterns("/*"); registration.tname("encryptfilter"); registration.torder(1);// registration.tenabled(fal); return registration; } //做跨域处理,跟这个filter没关系 @bean public webmvcconfigurer corsconfigurer() { return new webmvcconfigurer() { @override public void addcorsmappings(corsregistry registry) { registry.addmapping("/**") .allowedorigins("*") .allowcredentials(true) .allowedmethods("*") .allowedheaders("*") .maxage(3600); } }; }}
对于拦截路径上全部采用数据加解密处理,如果有部分接口不需要加解密处理的话,在方法上或者类上加上此注解即可不做加解密处理
package com.hars.common.infrastructure.validation.curity;import java.lang.annotation.documented;import java.lang.annotation.elementtype;import java.lang.annotation.retention;import java.lang.annotation.retentionpolicy;import java.lang.annota乡音不改tion.target;/** * 加解密注解 * * @author huangbigao * @date 2020/8/29 11:02 */@documented@target({elementtype.method, elementtype.type,})@retention(retentionpolicy.runtime)public @interface cryptodecryptioncurity { /** * 是否加解密,默认加解密 * * @return */ boolean cryptodecryption() default true; /** * 是否进行request 解密,默认进行解密 * * @return */ boolean requestdecryption() default true; /** * 是否对输出结果进行加密,默认进行加密 * * @return */ boolean responcrypto() default true;}
ps:注解使用
@cryptodecryptioncurity(responcrypto = fal) @apioperation(value = "微信公众号验证业务处理接口") @getmapping(value = "/handle/{appid}", produces = "text/plain;chart=utf-8") public string authhandle(@pathvariable string appid, @requestparam(name = "signature", required = fal) string signature, @requestparam(name = "timestamp", required = fal) string timestamp, @requestparam(name = "nonce", re熊猫的介绍quired = fal) string nonce, @requestparam(name = "echostr", required = fal) string echostr, httprvletrequest request) { return wechatmprvice.authhandle(appid, signature, timestamp, nonce, echostr, request); }
package com.hars.common.infrastructure.utils.filter;import com.alibaba.fastjson.json;import com.alibaba.fastjson.jsonobject;import com.alibaba.fastjson.typereference;import com.hars.common.infrastructure.utils.aes.aesutil;import com.hars.common.infrastructure.utils.http.httpcontextutil;import com.hars.common.infrastructure.utils.string.stringutil;import java.io.bytearrayinputstream;import java.io.ioexception;import java.io.inputstream;import java.util.collections;import java.util.enumeration;import java.util.hashmap;import java.util.linkedhasht;import java.util.map;import java.util.t;import javax.rvlet.readlistener;import javax.rvlet.rvletinputstream;import javax.rvlet.http.httprvletrequest;import javax.rvlet.http.httprvletrequestwrapper;import org.springframework.util.asrt;/** * @author huangbigao * @date 2020/8/29 10:12 */public class decryptionrequestutil extends httprvletrequestwrapper { private static final string application_json = "application/json"; /** * 所有参数的map集合 */ private map<string, string[]> parametermap; /** * 输入流 */ private inputstream inputstream; private final boolean valuevalid = true; public decryptionrequestutil(httprvletrequest request, string password) { super(request); string encrypt; string contenttype = request.getheader("content-type"); if (contenttype != null && contenttype.contains(application_json)) { //json string bodystr = httpcontextutil.getbodystring(request); if (stringutil.isblank(bodystr)){ return; } encrypt = (string) json.parobject(bodystr).get("encrypt"); } el { // url encrypt = request.getparameter("encrypt"); } string jsondata = aesutil.decrypt(encrypt, password); if (stringutil.isblank(jsondata)){ return; } if (contenttype != null && contenttype.contains(application_json)) { if (this.inputstream == null) { this.inputstream = new decryptioninputstream(new bytearrayinputstream(jsondata.getbytes())); } } parametermap = buildparams(jsondata); } private map<string, string[]> buildparams(string src) { map<string, string[]> map = new hashmap<>(); map<string, string> params = jsonobject.parobject(src, new typereference<map<string, string>>() { }); for (string key : params.keyt()) { map.put(key, new string[]{params.get(key)}); } return map; } @override public string getparameter(string name) { string[] values = getparametermap().get(name); if (valuevalid){ if (values != null) { return (values.length >海藻面膜功效 0 ? values[0] : null); } return super.getparameter(name); }el { return (values.length > 0 ? values[0] : null); } } @override public string[] getparametervalues(string name) { string[] values = getparametermap().get(name); if (valuevalid){ if (values != null) { return values; } return super.getparametervalues(name); }el { return values; } } @override public enumeration<string> getparameternames() { map<string, string[]> multipartparameters = getparametermap(); if (valuevalid){ if (multipartparameters.impty()) { return super.getparameternames(); } }el { if (multipartparameters.impty()) { return null; } } t<string> paramnames = new linkedhasht<>(); enumeration<string> paramenum = super.getparameternames(); while (paramenum.hasmoreelements()) { paramnames.add(paramenum.nextelement()); } paramnames.addall(multipartparameters.keyt()); return collections.enumeration(paramnames); } @override public map<string, string[]> getparametermap() { if (valuevalid){ return parametermap == null ? super.getparametermap() : parametermap; }el { return parametermap == null ? new hashmap<>() : parametermap; } } @override public rvletinputstream getinputstream() throws ioexception { if (valuevalid){ return this.inputstream == null ? super.getinputstream() : (rvletinputstream) this.inputstream; }el { return this.inputstream == null ? null : (rvletinputstream) this.inputstream; } } /** * 自定义rvletinputstream */ private class decryptioninputstream extends rvletinputstream { private final inputstream sourcestream; /** * create a delegatingrvletinputstream for the given source stream. * * @param sourcestream the source stream (never {@code null}) */ public decryptioninputstream(inputstream sourcestream) { asrt.notnull(sourcestream, "source inputstream must not be null"); this.sourcestream = sourcestream; } @override public int read() throws ioexception { return this.sourcestream.read(); } @override public void clo() throws ioexception { super.clo(); this.sourcestream.clo(); } @override public boolean isfinished() { return fal; } @override public boolean isready() { return fal; } @override public void treadlistener(readlistener readlistener) { } }}
package com.hars.common.infrastructure.utils.filter;import java.io.bytearrayoutputstream;import java.io.ioexception;import javax.rvlet.rvletoutputstream;import javax.rvlet.writelistener;import javax.rvlet.http.httprvletrespon;import javax.rvlet.http.httprvletresponwrapper;/** * @author huangbigao * @date 2020/8/29 13:11 */public class responwrapperutil extends httprvletresponwrapper { private bytearrayoutputstream buffer; private rvletoutputstream out; public responwrapperutil(httprvletrespon httprvletrespon) { super(httprvletrespon); buffer = new bytearrayoutputstream(); out = new wrapperoutputstream(buffer); } @override public rvletoutputstream getoutputstream() throws ioexception { return out; } @override public void flushbuffer() throws ioexception { if (out != null) { out.flush(); } } public byte[] getcontent() throws ioexception { flushbuffer(); return buffer.tobytearray(); } private static class wrapperoutputstream extends rvletoutputstream { private bytearrayoutputstream bos; wrapperoutputstream(bytearrayoutputstream bos) { this.bos = bos; } @override public void write(int b) throws ioexception { bos.write(b); } @override public boolean isready() { // todo auto-generated method stub return fal; } @override public void twritelistener(writelistener arg0) { // todo auto-generated method stub } }}
package com.hars.common.infrastructure.utils.aes;import com.hars.common.infrastructure.utils.string.stringutil;import java.nio.chart.standardcharts;import java.util.ba64;import javax.crypto.cipher;import javax.crypto.spec.cretkeyspec;import lombok.extern.slf4j.slf4j;/** * aes 加解密 工具类 * * @author huangbigao * @date 2020/8/28 15:17 */@slf4jpublic class aesutil { /** * aes解密 * * @param content 密文 * @param password 秘钥,必须为16个字符组成 * @return 明文 */ public static string decrypt(string content, string password) { try { if (stringutil.isblank(content) || stringutil.isblank(password)) { return null; } byte[] encryptbyte = ba64.getdecoder().decode(content); cipher cipher = cipher.getinstance("aes/ecb/pkcs5padding"); cipher.init(cipher.decrypt_mode, new cretkeyspec(password.getbytes(), "aes")); byte[] decryptbytes = cipher.dofinal(encryptbyte); return new string(decryptbytes); } catch (exception e) { log.error(e.getmessage(), e); return null; } } /** * aes加密 * * @param content 明文 * @param password 秘钥,必须为16个字符组成 * @return 密文 */ public static string encrypt(string content, string password) { try { if (stringutil.isblank(content) || stringutil.isblank(password)) { return null; } cipher cipher = cipher.getinstance("aes/ecb/pkcs5padding"); cipher.init(cipher.encrypt_mode, new cretkeyspec(password.getbytes(), "aes")); byte[] encryptstr = cipher.dofinal(content.getbytes(standardcharts.utf_8)); return ba64.getencoder().encodetostring(encryptstr); } catch (exception e) { log.error(e.getmessage(), e); return null; } }
package com.hars.ur.infrastructure.filter;import com.alibaba.fastjson.json;import com.hars.common.infrastructure.utils.aes.aesutil;import com.hars.common.infrastructure.utils.filter.decryptionrequestutil;import com.hars.common.infrastructure.utils.filter.responwrapperutil;import com.hars.common.infrastructure.validation.curity.cryptodecryptioncurity;import com.hars.result.infrastructure.advice.respon;import java.io.ioexception;import java.util.arraylist;import java.util.list;import java.util.map;import javax.rvlet.filter;import javax.rvlet.filterchain;import javax.rvlet.rvletexception;import javax.rvlet.rvletoutputstream;import javax.rvlet.rvletrequest;import javax.rvlet.rvletrespon;import javax.rvlet.http.httprvletrequest;import javax.rvlet.http.httprvletrespon;import org.springframework.beans.factory.beanfactoryutils;import org.springframework.context.applicationcontext;import org.springframework.core.annotation.annotationawareordercomparator;import org.springframework.web.method.handlermethod;import org.springframework.web.rvlet.handlerexecutionchain;import org.springframework.web.rvlet.handlermapping;/** * @author huangbigao * @date 2020/8/28 16:26 */public class cryptodecryptionfilter implements filter { //方法映射集 private list<handlermapping> handlermappings; public cryptodecryptionfilter(applicationcontext applicationcontext) { map<string, handlermapping> matchingbeans = beanfactoryutils.beansoftypeincludingancestors(applicationcontext, handlermapping.class, true, fal); if (!matchingbeans.impty()) { this.handlermappings = new arraylist<>(matchingbeans.values()); annotationawareordercomparator.sort(this.handlermappings); } } @override public void dofilter(rvletrequest request, rvletrespon respon, filterchain chain) throws ioexception, rvletexception { httprvletrequest httprvletrequest = (httprvletrequest) request; httprvletrespon httprvletrespon = (httprvletrespon) respon; //判断方法上是否存在注解,如果不存在,默认加解密 //类上的注解 cryptodecryptioncurity classflag = null; //方法上的注解 cryptodecryptioncurity methodflag = null; try { handlerexecutionchain handlerexecutionchain = gethandler(httprvletrequest); object handler = handlerexecutionchain != null ? handlerexecutionchain.gethandler() : null; if (handler instanceof handlermethod) { handlermethod method = (handlermethod) handler; classflag = method.getbeantype().getannotation(cryptodecryptioncurity.class); methodflag = method.getmethodannotation(cryptodecryptioncurity.class); //如果方法注解存在,且不加密,则直接返回 if (methodflag != null && !methodflag.cryptodecryption()) { chain.dofilter(request, respon); return; } //如果类注解存在,且不加密,则直接返回 if (classflag != null && !classflag.cryptodecryption()) { chain.dofilter(request, respon); return; } } } catch (exception e) { respon.tcontenttype("application/json; chart=utf-8"); respon.getwriter().write(json.tojsonstring(respon.error("该请求无效", 601))); return; } cryptodecryptioncurity currentflag = null; if (methodflag != null) { currentflag = methodflag; } el if (classflag != null) { currentflag = classflag; } //加解密密码 string password = "hbg584782648!@hb"; responwrapperutil responwrapper = null; //加解密处理 if (currentflag == null || (currentflag.requestdecryption() && currentflag.responcrypto())) { rvletrequest requestwrapper = new decryptionrequestutil(httprvletrequest, password); responwrapper = new responwrapperutil(httprvletrespon); chain.dofilter(requestwrapper, responwrapper); } el if (currentflag.requestdecryption() && !currentflag.responcrypto()) { rvletrequest requestwrapper = new decryptionrequestutil(httprvletrequest, password); chain.dofilter(requestwrapper, respon); } el if (!currentflag.requestdecryption() && currentflag.responcrypto()) { responwrapper = new responwrapperutil(httprvletrespon); chain.dofilter(request, responwrapper); } el { chain.dofilter(request, respon); } if (responwrapper != null) { byte[] content = responwrapper.getcontent();//获取返回值 //判断是否有值 if (content.length > 0) { string result = new string(content, "utf-8"); //加密 string encryptstr = aesutil.encrypt(result, password); //把返回值输出到客户端 rvletoutputstream out = respon.getoutputstream(); out.write(encryptstr.getbytes()); out.flush(); } } } /** * 获取访问目标方法 * * @param request * @return handlerexecutionchain * @throws exception */ private handlerexecutionchain gethandler(httprvletrequest request) throws exception { if (this.handlermappings != null) { for (handlermapping hm : this.handlermappings) { handlerexecutionchain handler = hm.gethandler(request); if (handler != null) { return handler; } } } return null; }}
@autowired private applicationcontext applicationcontext; /** * 添加加解密过滤器 * * @return */ @bean public filterregistrationbean encryptiondatafilterregistration() { filterregistrationbean<cryptodecryptionfilter> registration = new filterregistrationbean<>(); registration.tfilter(new cryptodecryptionfilter(applicationcontext)); registration.addurlpatterns("/*"); registration.tname("cryptodecryptionfilter"); registration.torder(2); return registration; }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。
本文发布于:2023-04-06 03:50:15,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/7a6a09dff0fe516b57c43901f73f8961.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:Springboot使用filter对response内容进行加密方式.doc
本文 PDF 下载地址:Springboot使用filter对response内容进行加密方式.pdf
留言与评论(共有 0 条评论) |