基于mybatis Interceptor的对 user_cache 表 address id_no 两个字段的加密解密;
生活随笔
收集整理的這篇文章主要介紹了
基于mybatis Interceptor的对 user_cache 表 address id_no 两个字段的加密解密;
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
軟件版本
- idea 2017.2
- mybatis:3.2.8
- java version "1.8.0_51"
common-config/src/main/resources/mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration><!-- 省略若干配置 --><!-- 插件配置 --><plugins><plugin interceptor="com.rd.ifaes.common.orm.interceptor.PaginationInterceptor" /><!-- 下面兩個(gè)是我添加的 --><plugin interceptor="com.rd.ifaes.core.core.interceptor.UpdateInterceptor"/><plugin interceptor="com.rd.ifaes.core.core.interceptor.ResultInterceptor"/></plugins> </configuration>core/src/main/java/com/rd/ifaes/core/core/interceptor/ResultInterceptor.java
package com.rd.ifaes.core.core.interceptor;import java.lang.reflect.Field; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties;import com.rd.ifaes.common.util.StringUtils; import org.apache.ibatis.executor.resultset.ResultSetHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.plugin.Intercepts; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.plugin.Plugin; import org.apache.ibatis.plugin.Signature;import com.rd.ifaes.common.orm.interceptor.BaseInterceptor; import com.rd.ifaes.common.util.ReflectionUtils; import com.rd.ifaes.common.util.AESUtils; import com.rd.ifaes.core.user.domain.UserCache;/*** Mybatis 攔截組件* @author leeyi* @version V1.0, 2018-01-10 11:16:20*/ @Intercepts( {@Signature(method = "handleResultSets", type = ResultSetHandler.class, args = {Statement.class})} ) public class ResultInterceptor extends BaseInterceptor {@Overridepublic Object intercept(Invocation invocation) throws Throwable {Object returnValue = invocation.proceed();if (returnValue instanceof ArrayList<?>) {List<?> list = (ArrayList<?>)returnValue;for(Object obj: list){if (obj instanceof UserCache) {// 查詢UserCache結(jié)果解密處理dealUserCacheReturnValue(obj);}}}return returnValue;}/*** 查詢UserCache結(jié)果解密處理*/private void dealUserCacheReturnValue(Object obj) {UserCache userCache = (UserCache)obj;// 這里只處理 addressString address = (String) ReflectionUtils.getFieldValue(obj, "address");userCache.setAddress(AESUtils.decryptForUsercache(address));// 這里只處理 idNoString idNo = (String) ReflectionUtils.getFieldValue(obj, "idNo");userCache.setIdNo(AESUtils.decryptForUsercache(idNo));}@Overridepublic Object plugin(Object target) {return Plugin.wrap(target, this);}@Overridepublic void setProperties(Properties properties) {System.out.println(properties.getProperty("databaseType"));} }core/src/main/java/com/rd/ifaes/core/core/interceptor/UpdateInterceptor.java
package com.rd.ifaes.core.core.interceptor;import java.util.Properties; import java.util.logging.Logger;import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.resultset.ResultSetHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.plugin.Intercepts; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.plugin.Plugin; import org.apache.ibatis.plugin.Signature;import com.rd.ifaes.common.orm.interceptor.BaseInterceptor; import com.rd.ifaes.common.util.ReflectionUtils; import com.rd.ifaes.common.util.PropertiesUtils; import com.rd.ifaes.common.util.AESUtils; import com.rd.ifaes.core.user.domain.UserCache;/*** Mybatis 攔截組件* @author leeyi* @version V1.0, 2018-01-10 11:16:20*/@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}) }) public class UpdateInterceptor extends BaseInterceptor {private final Logger logger = Logger.getLogger(String.valueOf(this.getClass()));private static final long serialVersionUID = 1L;private Object parameter;@Overridepublic Object intercept(Invocation invocation) throws Throwable {final MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];//攔截需要的SQLparameter = invocation.getArgs()[1];BoundSql boundSql = mappedStatement.getBoundSql(parameter);// 這里只捕獲 UserCache 其他 類型的不處理if (parameter instanceof UserCache) {Object obj = boundSql.getParameterObject();// UserCache 加密處理dealUserCacheValue(obj);}return invocation.proceed();}/*** UserCache 加密處理*/private void dealUserCacheValue(Object obj) {UserCache userCache = (UserCache)parameter;// 這里只處理 addressString address = (String) ReflectionUtils.getFieldValue(obj, "address");userCache.setAddress(AESUtils.encryptForUsercache(address));// 這里只處理 id_noString idNo = (String) ReflectionUtils.getFieldValue(obj, "idNo");userCache.setIdNo(AESUtils.encryptForUsercache(idNo));}@Overridepublic Object plugin(Object target) {return Plugin.wrap(target, this);}@Overridepublic void setProperties(Properties properties) {super.initProperties(properties);} }common-supports/src/main/java/com/rd/ifaes/common/util/AESUtils.java
package com.rd.ifaes.common.util;import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec;import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder;import com.rd.ifaes.common.util.PropertiesUtils;public class AESUtils {protected static String thisiv = "abc2030405060708";// iv 必須要是一個(gè)16為的字符串public static void setIv(String iv) {thisiv = iv;}/*** 加密* @method encrypt* @param strIn 需要加密的內(nèi)容* @param strKey 加密密碼* @return* @throws* @since v1.0*/public static String encrypt(String strKey, String strIn) throws Exception {SecretKeySpec skeySpec = getKey(strKey);Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");IvParameterSpec iv = new IvParameterSpec(thisiv.getBytes());cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);byte[] encrypted = cipher.doFinal(strIn.getBytes());return new BASE64Encoder().encode(encrypted);}/*** 解密* @method decrypt* @param strIn 待解密內(nèi)容* @param strKey 解密密鑰* @return* @throws* @since v1.0*/public static String decrypt(String strKey, String strIn) throws Exception {SecretKeySpec skeySpec = getKey(strKey);Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");IvParameterSpec iv = new IvParameterSpec(thisiv.getBytes());cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);byte[] encrypted1 = new BASE64Decoder().decodeBuffer(strIn);byte[] original = cipher.doFinal(encrypted1);String originalString = new String(original);return originalString;}/*** 將二進(jìn)制轉(zhuǎn)換成16進(jìn)制* @method parseByte2HexStr* @param buf* @return* @throws* @since v1.0*/private static String parseByte2HexStr(byte buf[]){StringBuffer sb = new StringBuffer();for(int i = 0; i < buf.length; i++){String hex = Integer.toHexString(buf[i] & 0xFF);if (hex.length() == 1) {hex = '0' + hex;}sb.append(hex.toUpperCase());}return sb.toString();}/*** 轉(zhuǎn)換密鑰<br>** @param strKey* @return* @throws Exception*/private static SecretKeySpec getKey(String strKey) throws Exception {byte[] arrBTmp = strKey.getBytes();byte[] arrB = new byte[16]; // 創(chuàng)建一個(gè)空的16位字節(jié)數(shù)組(默認(rèn)值為0)for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {arrB[i] = arrBTmp[i];}SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES");return skeySpec;}/*** 在獲取數(shù)據(jù)之前給數(shù)據(jù)解密 解密沒有成功的話,返回原來的值* @param param 需要加密的內(nèi)容* @return 解密后的字符串*/public static String decryptForUsercache(String param) {if (param == null || param.length() == 0) {return "";}if (param.length() < 4) {return param;}String prefix = param.substring(0,4);// 表示沒有加密if (!prefix.equals("aes:")) {return param;}try {final String key = PropertiesUtils.getValue("user_aes_encrypt_key");String ciphertext = param.substring(4);String plaintext = AESUtils.decrypt(key, ciphertext);param = plaintext;} catch(Exception e) {}return param;}/*** 在更新數(shù)據(jù)之前給數(shù)據(jù)加密* @param param 需要界面的內(nèi)容* @return 以 "aes:"開頭的字符串*/public static String encryptForUsercache(String param) {if (param == null || param.length() == 0) {return "";}if (param.length() < 4) {return param;}String prefix = param.substring(0,4);// 表示已經(jīng)加密過了if (prefix.equals("aes:")) {return param;}try {final String key = PropertiesUtils.getValue("user_aes_encrypt_key");param = "aes:" + AESUtils.encrypt(key, param);} catch(Exception e) {}return param;}public static void main(String[] args) throws Exception {String Code = "abcd";// String key = "1q2w3e4r*?";// String key = "1q2w3e4rei1q2w3e4rei";String key = "a3aMbVs6e6t2Ucy7";String codE, codePhp, codeObjc;AESUtils.setIv("abc2030405060708");codE = AESUtils.encrypt(key, Code);codePhp = "u6qq89cZALmD+1PX6dXRgA==";codeObjc = "MSVbpcJlzq/HqcpSoHA4SA==";System.out.println("原文:" + Code);System.out.println("密鑰:" + key);System.out.println("密文:" + codE);System.out.println("解密java:" + AESUtils.decrypt(key, codE));//System.out.println("解密php:" + AESUtils.decrypt(key, codePhp));//System.out.println("解密objc:" + AESUtils.decrypt(key, codeObjc));String address = "aes:peN5NYRurQT0deSQZ/SHwg==";String plaintext = AESUtils.decrypt("a3aMbVs6e6t2Ucy7", address.substring(4));System.out.println("ddd: " + plaintext);//String con2 = "5CxL+rE6Gh/zKPcffYExDg==";//System.out.println("解密objc:" + AESUtils.decrypt(key, con2));// String res = webview.postUrl("http://127.0.0.1:80","data=dhfakjsdfhksdhf+dfasjkdhf+adsfkhasld");// System.out.println("webview文:" + res);} }轉(zhuǎn)載于:https://my.oschina.net/leeyisoft/blog/1605184
總結(jié)
以上是生活随笔為你收集整理的基于mybatis Interceptor的对 user_cache 表 address id_no 两个字段的加密解密;的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OpenStack推出最新版本Newto
- 下一篇: ADT和DS