From f12d2c4c92dcd7929bce4d2df74f48f8abc08350 Mon Sep 17 00:00:00 2001 From: ChenJiaHe <763432473@qq.com> Date: 星期六, 22 一月 2022 10:17:43 +0800 Subject: [PATCH] Merge branch 'master' of https://gitee.com/huoxiong/hx_common --- src/main/java/com/hx/mybatis/aes/springbean/ConstantBean.java | 35 + src/main/java/com/hx/common/xml/CommonMapper.xml | 14 src/main/java/com/hx/mybatis/aes/springbean/InitMysqlData.java | 108 +++++ src/main/java/com/hx/common/service/impl/CommonServiceImpl.java | 8 src/main/java/com/hx/common/service/impl/CommonDaoImpl.java | 8 src/main/java/com/hx/util/mysql/aes/MysqlHexAesTool.java | 2 src/main/java/com/hx/common/dao/CommonMapper.java | 17 src/main/java/com/hx/common/dao/CommonDao.java | 9 src/main/java/com/hx/mybatis/aes/springbean/MySqlInterceptor.java | 97 ++++ src/main/java/com/hx/mybatis/aes/handler/GenericStringHandler.java | 72 +++ src/main/java/com/hx/mybatis/aes/springbean/SqlUtils.java | 500 +++++++++++++++++++++++ src/main/java/com/hx/common/annotations/MysqlHexAes.java | 22 + src/main/java/com/hx/mybatis/aes/springbean/ExportTableAliasVisitor.java | 53 ++ src/main/java/com/hx/common/service/CommonService.java | 9 src/main/java/com/hx/mybatis/aes/springbean/VariableAesKey.java | 289 +++++++++++++ 15 files changed, 1,240 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/hx/common/annotations/MysqlHexAes.java b/src/main/java/com/hx/common/annotations/MysqlHexAes.java new file mode 100644 index 0000000..4696b88 --- /dev/null +++ b/src/main/java/com/hx/common/annotations/MysqlHexAes.java @@ -0,0 +1,22 @@ +package com.hx.common.annotations; + +import java.lang.annotation.*; + +/** + * 鎸囧畾mysql鐨凙ES鍔犲瘑瀛楁 + * @author CJH + */ +@Target({ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface MysqlHexAes { + /**绉橀挜-娌℃湁灏辨槸閰嶇疆鏂囦欢璁剧疆*/ + String aesKey() default ""; + /**xml鐢熸垚鏌ヨ瑙e瘑*/ + boolean selectDec() default false; + /**xml鏇存柊鍔犲瘑*/ + boolean updateDec() default false; + /**xml鏂板鍔犲瘑*/ + boolean insertDec() default false; + +} \ No newline at end of file diff --git a/src/main/java/com/hx/common/dao/CommonDao.java b/src/main/java/com/hx/common/dao/CommonDao.java index 3a4ccad..3a5c32d 100644 --- a/src/main/java/com/hx/common/dao/CommonDao.java +++ b/src/main/java/com/hx/common/dao/CommonDao.java @@ -103,5 +103,12 @@ * @return 杩斿洖鏉℃暟 */ <T extends Serializable> int deleteById(Class<?> mapperClass, Object object); - + + /**鏇存柊sql璇彞锛堝叏璇彞锛� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int updateSentence( SqlSentence sqlSentence); + + } \ No newline at end of file diff --git a/src/main/java/com/hx/common/dao/CommonMapper.java b/src/main/java/com/hx/common/dao/CommonMapper.java new file mode 100644 index 0000000..4b29de2 --- /dev/null +++ b/src/main/java/com/hx/common/dao/CommonMapper.java @@ -0,0 +1,17 @@ +package com.hx.common.dao; + +import com.hx.mybatisTool.SqlSentence; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +public interface CommonMapper { + + /**鏇存柊锛岃繑鍥炴洿鏂版暟閲�*/ + int updateSentence(SqlSentence sqlSentence); + + /**鏌ヨ鍒楄〃锛岃繑鍥濵ap鐨凩ist*/ + List<Map<String,Object>> selectListMap(SqlSentence sqlSentence); + +} \ No newline at end of file diff --git a/src/main/java/com/hx/common/service/CommonService.java b/src/main/java/com/hx/common/service/CommonService.java index 2d35f9f..312786c 100644 --- a/src/main/java/com/hx/common/service/CommonService.java +++ b/src/main/java/com/hx/common/service/CommonService.java @@ -104,5 +104,12 @@ * @return 杩斿洖鏉℃暟 */ <T extends Serializable> int deleteById(Class<?> mapperClass, Object object); - + + /**鏇存柊sql璇彞锛堝叏璇彞锛� + * @param sqlSentence 鏌ヨ鍙傛暟绫� + * @return 杩斿洖鏉℃暟 + */ + <T extends Serializable> int updateSentence(SqlSentence sqlSentence); + + } \ No newline at end of file diff --git a/src/main/java/com/hx/common/service/impl/CommonDaoImpl.java b/src/main/java/com/hx/common/service/impl/CommonDaoImpl.java index 16ef362..685e468 100644 --- a/src/main/java/com/hx/common/service/impl/CommonDaoImpl.java +++ b/src/main/java/com/hx/common/service/impl/CommonDaoImpl.java @@ -1,6 +1,7 @@ package com.hx.common.service.impl; import com.hx.common.dao.CommonDao; +import com.hx.common.dao.CommonMapper; import com.hx.mybatisTool.SqlSentence; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.stereotype.Service; @@ -102,4 +103,11 @@ return sqlSessionFactory.openSession().delete(getStatement(mapperClass,"deleteById"),object); } + /**鏇存柊sql璇彞锛堝叏璇彞锛�*/ + @Override + public <T extends Serializable> int updateSentence(SqlSentence sqlSentence) { + return sqlSessionFactory.openSession().delete(getStatement(CommonMapper.class,"updateSentence"),sqlSentence); + } + + } diff --git a/src/main/java/com/hx/common/service/impl/CommonServiceImpl.java b/src/main/java/com/hx/common/service/impl/CommonServiceImpl.java index c2822ec..078f8d2 100644 --- a/src/main/java/com/hx/common/service/impl/CommonServiceImpl.java +++ b/src/main/java/com/hx/common/service/impl/CommonServiceImpl.java @@ -97,4 +97,12 @@ return commonDao.deleteById(mapperClass,object); } + + /**鏇存柊sql璇彞锛堝叏璇彞锛�*/ + @Override + public <T extends Serializable> int updateSentence(SqlSentence sqlSentence) { + return commonDao.updateSentence(sqlSentence); + } + + } diff --git a/src/main/java/com/hx/common/xml/CommonMapper.xml b/src/main/java/com/hx/common/xml/CommonMapper.xml new file mode 100644 index 0000000..968338a --- /dev/null +++ b/src/main/java/com/hx/common/xml/CommonMapper.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<!DOCTYPE mapper +PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" +"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> +<!-- namespace:璇apper.xml鏄犲皠鏂囦欢鐨� 鍞竴鏍囪瘑 --> +<mapper namespace="com.hx.common.dao.CommonMapper"> + <update id="updateSentence" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </update> + + <select id="selectListMap" resultType="java.util.Map" parameterType="com.hx.mybatisTool.SqlSentence" > + ${sqlSentence} + </select> +</mapper> \ No newline at end of file diff --git a/src/main/java/com/hx/mybatis/aes/handler/GenericStringHandler.java b/src/main/java/com/hx/mybatis/aes/handler/GenericStringHandler.java new file mode 100644 index 0000000..2598bdf --- /dev/null +++ b/src/main/java/com/hx/mybatis/aes/handler/GenericStringHandler.java @@ -0,0 +1,72 @@ +package com.hx.mybatis.aes.handler; + +import com.hx.mybatis.aes.springbean.VariableAesKey; +import com.hx.util.mysql.aes.MysqlHexAesTool; +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; +import org.apache.ibatis.type.MappedJdbcTypes; +import org.apache.ibatis.type.MappedTypes; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * @author CJH + * @Date 2021-01-02 + * // @MappedTypes娉ㄨВ涓殑绫讳唬琛ㄦ杞崲鍣ㄥ彲浠ヨ嚜鍔ㄨ浆鎹负鐨刯ava瀵硅薄锛孈MappedJdbcTypes娉ㄨВ涓缃殑鏄搴旂殑jdbctype锛宮ysql鐨刯son瀵硅薄瀵瑰簲鐨刯dbctype涓篤ARCHAR銆� + */ +@MappedTypes(value = {String.class}) +@MappedJdbcTypes(value = {JdbcType.VARCHAR}, includeNullJdbcType = true) +public class GenericStringHandler extends BaseTypeHandler<String> { + + public GenericStringHandler() { + } + + @Override + public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException { + ps.setString(i, parameter); + } + + @Override + public String getNullableResult(ResultSet rs, String columnName) throws SQLException { + String data = rs.getString(columnName); + if(data != null && data.length()%32==0 && MysqlHexAesTool.isHexStrValid(data)){ + try{ + data = MysqlHexAesTool.decryptData(data, VariableAesKey.getAesKey(columnName),null); + }catch (Exception e){ + //e.printStackTrace(); + } + } + return data; + } + + @Override + public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + String data = rs.getString(columnIndex); + if(data != null && data.length()%32==0 && MysqlHexAesTool.isHexStrValid(data)){ + try{ + data = MysqlHexAesTool.decryptData(data, VariableAesKey.getAesKey(null),null); + }catch (Exception e){ + //e.printStackTrace(); + } + } + return data; + } + + @Override + public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + String data = cs.getString(columnIndex); + if(data != null && data.length() < 129 && data.length()%32==0 && MysqlHexAesTool.isHexStrValid(data)){ + try{ + data = MysqlHexAesTool.decryptData(data, VariableAesKey.getAesKey(null),null); + }catch (Exception e){ + //e.printStackTrace(); + } + } + return data; + } + +} + diff --git a/src/main/java/com/hx/mybatis/aes/springbean/ConstantBean.java b/src/main/java/com/hx/mybatis/aes/springbean/ConstantBean.java new file mode 100644 index 0000000..d64a839 --- /dev/null +++ b/src/main/java/com/hx/mybatis/aes/springbean/ConstantBean.java @@ -0,0 +1,35 @@ +package com.hx.mybatis.aes.springbean; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * 閫氱敤甯搁噺闆嗕腑钀� + * @author CJH + */ +@Component +public class ConstantBean { + + /**鑾峰彇AES绉橀挜鐨勯厤缃紙浠庝粈涔堝寘鑾峰彇鍒帮級*/ + @Value("${mysql.hxe.aes.find.packs:null}") + private String packPath; + /**鍥哄畾AES鐨勭閽�*/ + @Value("${mysql.hxe.aes.fixd.key:null}") + private String fixedAesKey; + + public String getPackPath() { + return packPath; + } + + public void setPackPath(String packPath) { + this.packPath = packPath; + } + + public String getFixedAesKey() { + return fixedAesKey; + } + + public void setFixedAesKey(String fixedAesKey) { + this.fixedAesKey = fixedAesKey; + } +} diff --git a/src/main/java/com/hx/mybatis/aes/springbean/ExportTableAliasVisitor.java b/src/main/java/com/hx/mybatis/aes/springbean/ExportTableAliasVisitor.java new file mode 100644 index 0000000..78d4c32 --- /dev/null +++ b/src/main/java/com/hx/mybatis/aes/springbean/ExportTableAliasVisitor.java @@ -0,0 +1,53 @@ +package com.hx.mybatis.aes.springbean; + +import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; +import com.alibaba.druid.sql.visitor.SQLASTVisitorAdapter; + +import java.util.HashMap; +import java.util.Map; + +/** + * ExportTableAliasVisitor + * @author Mwg + * @date 2020/09/08 23:47 + */ +public class ExportTableAliasVisitor extends SQLASTVisitorAdapter { + + private Map<String,String> tableMap = new HashMap<>(); + + public Map<String, String> getTableMap() { + return tableMap; + } + + public void setTableMap(Map<String, String> tableMap) { + this.tableMap = tableMap; + } + + @Override + public boolean visit(SQLExprTableSource x) { + + //鍒悕锛屽鏋滄湁鍒悕锛屽埆鍚嶄繚鎸佷笉鍙� + //System.out.println("alias:"+x.getAlias());//鍒悕 + //System.out.println("expr:"+x.getExpr());//琛ㄥ悕 + tableMap.put(x.getExpr().toString(),x.getAlias()); + + + //String s = StringUtils.isEmpty(x.getAlias()) ? x.getExpr().toString() : x.getAlias(); + + // 淇敼琛ㄥ悕锛屼笉鍖呭惈鐐规墠鍔� select id from c left join d on c.id = d.id 涓殑c 鍜� d + + /*if(!x.getExpr().toString().contains(".")) { + + x.setExpr("`" + dbName.get() + "`." + x.getExpr()); + + }*/ + //x.setExpr("mymymytable");//淇敼琛ㄥ悕 + //x.setAlias("aa");//淇敼鍒悕 + //x.setAlias(s); + return true; + + } + + + +} \ No newline at end of file diff --git a/src/main/java/com/hx/mybatis/aes/springbean/InitMysqlData.java b/src/main/java/com/hx/mybatis/aes/springbean/InitMysqlData.java new file mode 100644 index 0000000..2c5abcc --- /dev/null +++ b/src/main/java/com/hx/mybatis/aes/springbean/InitMysqlData.java @@ -0,0 +1,108 @@ +package com.hx.mybatis.aes.springbean; + +import com.gitee.sunchenbin.mybatis.actable.annotation.Column; +import com.gitee.sunchenbin.mybatis.actable.annotation.Table; +import com.hx.common.annotations.MysqlHexAes; +import com.hx.common.dao.CommonMapper; +import com.hx.common.service.CommonService; +import com.hx.exception.ServiceException; +import com.hx.mybatisTool.SqlSentence; +import com.hx.util.StringUtils; +import com.hx.util.mysql.aes.MysqlHexAesTool; + +import javax.annotation.PostConstruct; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class InitMysqlData { + + /** + * 椤圭洰鍚姩灏辨墽琛屽悗灏辨墽琛岃鏂规硶 + */ + @PostConstruct + public static void initData(String packPath, CommonService commonService){ + + //椤圭洰鍚姩鐨勬椂鍊欏~鍏� + if(!StringUtils.isEmpty(packPath)){ + Set<Class<?>> classes = VariableAesKey.classData(packPath); + Map<String,String> aesKeysFild = new HashMap<>(); + boolean isAes = false; + String tableName = null; + String fildName = null; + String fildValue = null; + + SqlSentence sqlSentence = new SqlSentence(); + Map<String,Object> values = new HashMap<>(); + + for(Class<?> cl:classes){ + //琛ㄥ悕绉� + boolean hasAnnotation = cl.isAnnotationPresent(Table.class); + if(!hasAnnotation){ + continue; + } + Table table = cl.getAnnotation(Table.class); + tableName = table.name(); + + aesKeysFild = new HashMap<>(); + isAes = false; + + // 鍙栧緱鏈被鐨勫叏閮ㄥ睘鎬� + Field[] fields = cl.getDeclaredFields(); + fields = VariableAesKey.getPatentFields(fields,cl); + for (Field field:fields) { + fildName = null; + // 鍒ゆ柇鏂规硶涓槸鍚︽湁鎸囧畾娉ㄨВ绫诲瀷鐨勬敞瑙� + hasAnnotation = field.isAnnotationPresent(MysqlHexAes.class); + if (hasAnnotation) { + // 鏍规嵁娉ㄨВ绫诲瀷杩斿洖鏂规硶鐨勬寚瀹氱被鍨嬫敞瑙� + MysqlHexAes mysqlHexAes = field.getAnnotation(MysqlHexAes.class); + + //String aesKeyField = mysqlHexAes.aesKeyField(); + String aesKey = mysqlHexAes.aesKey(); + + if(StringUtils.isEmpty(aesKey)){ + aesKey = VariableAesKey.AES_KEY; + if(StringUtils.isEmpty(aesKey)){ + throw new RuntimeException("mysql鐨凙ES绉橀挜涓嶈兘涓虹┖:"+field.getName()); + } + } + + hasAnnotation = field.isAnnotationPresent(Column.class); + if(hasAnnotation){ + Column column = field.getAnnotation(Column.class); + fildName = column.name(); + } + if(StringUtils.isEmpty(fildName)){ + fildName = field.getName(); + } + + sqlSentence.sqlSentence("SELECT id,"+fildName+" FROM "+tableName,values); + List<Map<String,Object>> list = commonService.selectListMap(CommonMapper.class,sqlSentence); + for(Map<String,Object> map:list){ + fildValue = (String)map.get(fildName); + System.out.println("fildValue:"+fildValue); + if(StringUtils.isEmpty(fildValue)){ + continue; + } + if(fildValue.length()%32==0 && MysqlHexAesTool.isHexStrValid(fildValue)){ + continue; + } + values.clear(); + values.put("id",map.get("id")); + values.put("filedData",fildValue); + sqlSentence.sqlSentence("UPDATE "+tableName+" SET "+fildName+" = #{m.filedData} WHERE id = #{m.id}",values); + if(commonService.updateSentence(sqlSentence)!=1){ + throw new ServiceException("鏇存柊瓒呰繃1鏉★紝鏇存柊澶辫触锛�"); + } + } + } + } + } + } + } + + +} diff --git a/src/main/java/com/hx/mybatis/aes/springbean/MySqlInterceptor.java b/src/main/java/com/hx/mybatis/aes/springbean/MySqlInterceptor.java new file mode 100644 index 0000000..71684ef --- /dev/null +++ b/src/main/java/com/hx/mybatis/aes/springbean/MySqlInterceptor.java @@ -0,0 +1,97 @@ +package com.hx.mybatis.aes.springbean; + +import org.apache.ibatis.executor.statement.StatementHandler; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.mapping.ParameterMapping; +import org.apache.ibatis.mapping.SqlCommandType; +import org.apache.ibatis.plugin.*; +import org.apache.ibatis.reflection.DefaultReflectorFactory; +import org.apache.ibatis.reflection.MetaObject; +import org.apache.ibatis.reflection.SystemMetaObject; +import org.apache.ibatis.session.Configuration; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Field; +import java.sql.Connection; +import java.util.List; +import java.util.Properties; + + +@Component +@Intercepts({ + @Signature( + type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class + }) +}) +public class MySqlInterceptor implements Interceptor { + @Override + public Object intercept(Invocation invocation) throws Throwable { + + // 鏂规硶涓� + StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); + MetaObject metaObject = MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory()); + //鍏堟嫤鎴埌RoutingStatementHandler锛岄噷闈㈡湁涓猄tatementHandler绫诲瀷鐨刣elegate鍙橀噺锛屽叾瀹炵幇绫绘槸BaseStatementHandler锛岀劧鍚庡氨鍒癇aseStatementHandler鐨勬垚鍛樺彉閲弇appedStatement + MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement"); + //id涓烘墽琛岀殑mapper鏂规硶鐨勫叏璺緞鍚嶏紝濡俢om.uv.dao.UserMapper.insertUser + //String id = mappedStatement.getId(); + //sql璇彞绫诲瀷 select銆乨elete銆乮nsert銆乽pdate + SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType(); + BoundSql boundSql = statementHandler.getBoundSql(); + + // 鑾峰彇鑺傜偣鐨勯厤缃� + Configuration configuration = mappedStatement.getConfiguration(); + // 鑾峰彇鍙傛暟 + Object parameterObject = boundSql.getParameterObject(); + // MetaObject涓昏鏄皝瑁呬簡originalObject瀵硅薄锛屾彁渚涗簡get鍜宻et鐨勬柟娉曠敤浜庤幏鍙栧拰璁剧疆originalObject鐨勫睘鎬у��,涓昏鏀寔瀵笿avaBean銆丆ollection銆丮ap涓夌绫诲瀷瀵硅薄鐨勬搷浣� + // MetaObject metaObject1 = configuration.newMetaObject(parameterObject); + //鑾峰彇sql涓棶鍙风殑鍩烘湰淇℃伅 + List<ParameterMapping> parameterMappings = boundSql + .getParameterMappings(); + + /*for (ParameterMapping parameterMapping : parameterMappings) { + String propertyName = parameterMapping.getProperty(); + System.out.println("propertyName锛�"+ propertyName); + System.out.println("parameterObject锛�"+ parameterObject); + }*/ + + //杩欓噷鍙互杩涜sql淇敼 + //鑾峰彇鍒板師濮媠ql璇彞 + String sql = boundSql.getSql(); + + //鏂板 + if(sqlCommandType == SqlCommandType.INSERT){ + sql = SqlUtils.insertSql(sql, VariableAesKey.aesKeysTable); + }else if(sqlCommandType == SqlCommandType.UPDATE){ + sql = SqlUtils.updateSql(sql, VariableAesKey.aesKeysTable); + }else if(sqlCommandType == SqlCommandType.SELECT){ + if(VariableAesKey.isRun == 1){ + sql = SqlUtils.selectSql(sql, VariableAesKey.aesKeysTable); + } + }else if(sqlCommandType == SqlCommandType.DELETE){ + sql = SqlUtils.deleteSql(sql, VariableAesKey.aesKeysTable); + } + + //閫氳繃鍙嶅皠淇敼sql璇彞 + Field field = boundSql.getClass().getDeclaredField("sql"); + field.setAccessible(true); + field.set(boundSql, sql); + return invocation.proceed(); + + } + + @Override + public Object plugin(Object target) { + if (target instanceof StatementHandler) { + return Plugin.wrap(target, this); + } else { + return target; + } + + } + + @Override + public void setProperties(Properties properties) { + + } +} \ No newline at end of file diff --git a/src/main/java/com/hx/mybatis/aes/springbean/SqlUtils.java b/src/main/java/com/hx/mybatis/aes/springbean/SqlUtils.java new file mode 100644 index 0000000..597aa0e --- /dev/null +++ b/src/main/java/com/hx/mybatis/aes/springbean/SqlUtils.java @@ -0,0 +1,500 @@ +package com.hx.mybatis.aes.springbean; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.SQLObject; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.ast.statement.*; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlDeleteStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlInsertStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlUpdateStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.visitor.SQLASTOutputVisitor; +import com.alibaba.druid.stat.TableStat; +import com.alibaba.druid.util.JdbcConstants; +import com.alibaba.druid.util.JdbcUtils; +import com.hx.util.StringUtils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +/** + * sql璇彞澶勭悊宸ュ叿 + * @author CJH 2022-01-12 + */ +public class SqlUtils { + + /**鏌ヨ鍔犲瘑鏁版嵁澶勭悊锛屽彧瀵规煡璇㈠仛澶勭悊锛宻elect杩斿洖涓嶅仛澶勭悊 + * @param sql sql璇彞 + * @param aesKeysTable aes绉橀挜 + * @return + */ + public static String selectSql(String sql,Map<String,Map<String,String>> aesKeysTable){ + + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLSelectStatement sqlStatement = (SQLSelectStatement) parser.parseSelect(); + //鑾峰彇鏍煎紡鍖栫殑slq璇彞 + sql = sqlStatement.toString(); + + //瑙f瀽select鏌ヨ + //SQLSelect sqlSelect = sqlStatement.getSelect() + //鑾峰彇sql鏌ヨ鍧� + SQLSelectQueryBlock sqlSelectQuery = (SQLSelectQueryBlock)sqlStatement.getSelect().getQuery() ; + StringBuffer out = new StringBuffer() ; + //鍒涘缓sql瑙f瀽鐨勬爣鍑嗗寲杈撳嚭 + SQLASTOutputVisitor sqlastOutputVisitor = SQLUtils.createFormatOutputVisitor(out , null , JdbcUtils.MYSQL) ; + + //鑾峰彇琛ㄥ拰鍒悕 + ExportTableAliasVisitor visitorTable = new ExportTableAliasVisitor(); + sqlStatement.accept(visitorTable); + Map<String,String> tableMaps = visitorTable.getTableMap(); + + //鑾峰彇鎵�鏈夌殑瀛楁 + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + sqlStatement.accept(visitor); + //閬嶅巻鎵�鏈夊瓧娈� + Collection<TableStat.Column> columns= visitor.getColumns(); + + StringBuilder sqlWhere = new StringBuilder(); + + StringBuilder sqlSelect = new StringBuilder(); + String expr = null; + sqlSelect.append("SELECT "); + //瑙f瀽select杩斿洖鐨勬暟鎹瓧娈甸」 + for (SQLSelectItem sqlSelectItem : sqlSelectQuery.getSelectList()) { + if(sqlSelect.length() > 7){ + sqlSelect.append(","); + } + + out.delete(0, out.length()) ; + sqlSelectItem.accept(sqlastOutputVisitor) ; + expr = out.toString(); + sqlSelect.append(expr); + + /* if(expr.indexOf("SELECT") == -1){ + sqlSelect.append(expr); + }else{ + //sqlSelect.append("("); + sqlSelect.append(expr); + //sqlSelect.append(")"); + *//* if(!StringUtils.isEmpty(sqlSelectItem.getAlias())){ + sqlSelect.append(" AS "+sqlSelectItem.getAlias()); + }*//* + }*/ + } + + //瑙f瀽from + if(sqlSelectQuery.getFrom() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getFrom().accept(sqlastOutputVisitor) ; + sqlWhere.append(" FROM "+out); + } + + //瑙f瀽where + if(sqlSelectQuery.getWhere() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getWhere().accept(sqlastOutputVisitor) ; + sqlWhere.append(" WHERE "+out+" "); + } + + if(sqlSelectQuery.getGroupBy() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getGroupBy().accept(sqlastOutputVisitor) ; + sqlWhere.append(" "+out); + } + if(sqlSelectQuery.getOrderBy() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getOrderBy().accept(sqlastOutputVisitor) ; + sqlWhere.append(" "+out); + } + if(sqlSelectQuery.getLimit() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getLimit().accept(sqlastOutputVisitor) ; + sqlWhere.append(" "+out); + } + + //澶勭悊where闇�瑕佸姞瀵嗗緱瀛楁 + sql = sqlWhere.toString(); + if(!StringUtils.isEmpty(sql)){ + Map<String,String> aesKeys = null; + String aeskey = null; + //鎶婂墿涓嬬殑鎷兼帴涓婃潵 + String tableAl = null; + for(TableStat.Column column:columns){ + aesKeys= aesKeysTable.get(column.getTable()); + if(aesKeys == null){ + continue; + } + aeskey = aesKeys.getOrDefault(column.getName(),null); + if(StringUtils.isEmpty(aeskey)){ + continue; + } + tableAl = tableMaps.get(column.getTable()); + if(!StringUtils.isEmpty(tableAl)){ + tableAl = tableAl+"."+column.getName(); + }else{ + tableAl = column.getName(); + } + sql = sql.replaceAll("\\b"+tableAl+"\\b","AES_DECRYPT(UNHEX("+tableAl+"),'"+aeskey+"')"); + } + } + return sqlSelect.toString()+sql; + } + + /** + * 澶勭悊select杩斿洖瀛楁鐨勫弬鏁� + * @param sql + * @param aesKeysTable + * @param tableMaps + * @param columns + * @return + */ + public static String selectSqlHandle(String sql,Map<String,Map<String,String>> aesKeysTable + ,Map<String,String> tableMaps,Collection<TableStat.Column> columns){ + + + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLSelectStatement sqlStatement = (SQLSelectStatement) parser.parseSelect(); + //鑾峰彇鏍煎紡鍖栫殑slq璇彞 + sql = sqlStatement.toString(); + + //瑙f瀽select鏌ヨ + //SQLSelect sqlSelect = sqlStatement.getSelect() ; + //鑾峰彇sql鏌ヨ鍧� + SQLSelectQueryBlock sqlSelectQuery = (SQLSelectQueryBlock)sqlStatement.getSelect().getQuery() ; + StringBuffer out = new StringBuffer() ; + //鍒涘缓sql瑙f瀽鐨勬爣鍑嗗寲杈撳嚭 + SQLASTOutputVisitor sqlastOutputVisitor = SQLUtils.createFormatOutputVisitor(out , null , JdbcUtils.MYSQL) ; + + StringBuilder sqlWhere = new StringBuilder(); + + StringBuilder sqlSelect = new StringBuilder(); + String expr = null; + sqlSelect.append("SELECT "); + //瑙f瀽select杩斿洖鐨勬暟鎹瓧娈甸」 + for (SQLSelectItem sqlSelectItem : sqlSelectQuery.getSelectList()) { + if(sqlSelect.length() > 7){ + sqlSelect.append(","); + } + expr = sqlSelectItem.getExpr().toString(); + if(expr.indexOf("SELECT") == -1){ + sqlSelect.append(expr); + if(!StringUtils.isEmpty(sqlSelectItem.getAlias())){ + sqlSelect.append(" AS "+sqlSelectItem.getAlias()); + } + }else{ + sqlSelect.append("("); + selectSqlHandle(expr,aesKeysTable,tableMaps,columns); + sqlSelect.append(")"); + if(!StringUtils.isEmpty(sqlSelectItem.getAlias())){ + sqlSelect.append(" AS "+sqlSelectItem.getAlias()); + } + } + } + + //瑙f瀽from + if(sqlSelectQuery.getFrom() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getFrom().accept(sqlastOutputVisitor) ; + sqlWhere.append(" FROM "+out); + } + + //瑙f瀽where + if(sqlSelectQuery.getWhere() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getWhere().accept(sqlastOutputVisitor) ; + sqlWhere.append(" WHERE "+out+" "); + } + + if(sqlSelectQuery.getGroupBy() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getGroupBy().accept(sqlastOutputVisitor) ; + sqlWhere.append(" "+out); + } + if(sqlSelectQuery.getOrderBy() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getOrderBy().accept(sqlastOutputVisitor) ; + sqlWhere.append(" "+out); + } + if(sqlSelectQuery.getLimit() != null){ + out.delete(0, out.length()) ; + sqlSelectQuery.getLimit().accept(sqlastOutputVisitor) ; + sqlWhere.append(" "+out); + } + + sql = sqlWhere.toString(); + if(!StringUtils.isEmpty(sql)){ + Map<String,String> aesKeys = null; + String aeskey = null; + //鎶婂墿涓嬬殑鎷兼帴涓婃潵 + String tableAl = null; + + for(TableStat.Column column:columns){ + aesKeys= aesKeysTable.get(column.getTable()); + if(aesKeys == null){ + continue; + } + aeskey = aesKeys.getOrDefault(column.getName(),null); + if(StringUtils.isEmpty(aeskey)){ + continue; + } + tableAl = tableMaps.get(column.getTable()); + if(!StringUtils.isEmpty(tableAl)){ + tableAl = tableAl+"."+column.getName(); + }else{ + tableAl = column.getName(); + } + sql = sql.replaceAll("\\b"+tableAl+"\\b","AES_DECRYPT(UNHEX("+tableAl+"),'"+aeskey+"')"); + } + } + return sqlSelect.toString()+sql; + } + + /**鏂板鍔犲瘑鏁版嵁澶勭悊 + * @param sql sql璇彞 + * @param aesKeysTable aes绉橀挜 + * @return + */ + public static String insertSql(String sql,Map<String,Map<String,String>> aesKeysTable){ + //瑁呰浇閲嶅啓鐨剆ql璇彞 + StringBuilder splicingSql = new StringBuilder(); + + sql = SQLUtils.format(sql, JdbcConstants.MYSQL); + String[] datas = sql.split("VALUES",2); + + splicingSql.append(datas[0]+"VALUES "); + + //閲嶆柊鎷兼帴SQL璇彞 + + //瑙f瀽sql璇彞 + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement statement = parser.parseStatement(); + MySqlInsertStatement insert = (MySqlInsertStatement)statement; + + String insertName = insert.getTableName().getSimpleName(); + + //鏍规嵁琛ㄥ悕绉拌幏鍙栧埌AES绉橀挜 + Map<String,String> aesKeys= aesKeysTable.get(insertName); + if(aesKeys == null){ + return sql; + } + + //鑾峰彇鎵�鏈夌殑瀛楁 + List<SQLExpr> columns = insert.getColumns(); + + String fildValue = null; + String aeskey = null; + //閬嶅巻鍊� + List<SQLInsertStatement.ValuesClause> vcl = insert.getValuesList(); + for(int j = 0; j<vcl.size(); j++){ + if( j != 0){ + splicingSql.append(","); + } + for(int i = 0;i < columns.size();i++){ + //鏌ヨ鏀瑰瓧娈垫槸鍚﹂渶瑕佸姞瀵� + aeskey = aesKeys.getOrDefault(columns.get(i).toString(),null); + fildValue = vcl.get(j).getValues().get(i).toString(); + if(i == 0){ + splicingSql.append("("); + if(aeskey != null && fildValue.indexOf("AES_ENCRYPT") == -1){ + splicingSql.append("HEX(AES_ENCRYPT("+fildValue+",'"+aeskey+"'))"); + }else{ + splicingSql.append(fildValue); + } + }else if(i == columns.size()-1){ + splicingSql.append(","); + if(aeskey != null && fildValue.indexOf("AES_ENCRYPT") == -1){ + splicingSql.append("HEX(AES_ENCRYPT("+fildValue+",'"+aeskey+"'))"); + }else{ + splicingSql.append(fildValue); + } + splicingSql.append(")"); + }else{ + splicingSql.append(","); + if(aeskey != null && fildValue.indexOf("AES_ENCRYPT") == -1){ + splicingSql.append("HEX(AES_ENCRYPT("+fildValue+",'"+aeskey+"'))"); + }else{ + splicingSql.append(fildValue); + } + } + } + } + return splicingSql.toString(); + } + + /**鏇存柊鍔犲瘑鏁版嵁澶勭悊 + * @param sql sql璇彞 + * @param aesKeysTable aes绉橀挜 + * @return + */ + public static String updateSql(String sql,Map<String,Map<String,String>> aesKeysTable){ + + //瑁呰浇閲嶅啓鐨剆ql璇彞 + StringBuilder splicingSql = new StringBuilder(); + + //sql = SQLUtils.format(sql, JdbcConstants.MYSQL); + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement sqlStatement = parser.parseStatement(); + //鑾峰彇鏍煎紡鍖栫殑slq璇彞 + sql = sqlStatement.toString(); + + MySqlUpdateStatement updateStatement = (MySqlUpdateStatement)sqlStatement; + + String insertName = updateStatement.getTableName().getSimpleName(); + + String[] datas = sql.split("WHERE",2); + + Map<String,String> aesKeys = aesKeysTable.get(insertName); + if(aesKeys == null){ + return sql; + } + + splicingSql.append("UPDATE "+insertName+" SET "); + String aeskey = null; + String fildValue = null; + List<SQLUpdateSetItem> items = updateStatement.getItems(); + for(int i = 0;i<items.size();i++){ + if(i != 0){ + splicingSql.append(","); + } + SQLUpdateSetItem item = items.get(i); + //鏌ヨ鏀瑰瓧娈垫槸鍚﹂渶瑕佸姞瀵� + aeskey = aesKeys.getOrDefault(item.getColumn().toString(),null); + + fildValue = item.getValue().toString(); + if(aeskey != null && fildValue.indexOf("AES_ENCRYPT") == -1){ + splicingSql.append(item.getColumn()+" = HEX(AES_ENCRYPT("+fildValue+",'"+aeskey+"'))"); + }else{ + splicingSql.append(item.getColumn()+" = "+fildValue); + } + } + String sqlWhere = " WHERE"; + //鎶婂墿涓嬬殑鎷兼帴涓婃潵 + if(datas.length > 1){ + for(int i =1;i<datas.length;i++){ + sqlWhere = sqlWhere+datas[i]; + } + + parser = new MySqlStatementParser("SELECT * FROM "+insertName+" "+sqlWhere); + sqlStatement = parser.parseStatement(); + + ExportTableAliasVisitor visitorTable = new ExportTableAliasVisitor(); + sqlStatement.accept(visitorTable); + + //鑾峰彇琛ㄥ拰鍒悕 + Map<String,String> tableMaps = visitorTable.getTableMap(); + tableMaps.put(insertName,null); + + //鑾峰彇鎵�鏈夌殑瀛楁 + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + sqlStatement.accept(visitor); + + String tableAl = null; + //閬嶅巻鎵�鏈夊瓧娈� + Collection<TableStat.Column> columns= visitor.getColumns(); + for(TableStat.Column column:columns){ + + aesKeys= aesKeysTable.get(column.getTable()); + if(aesKeys == null){ + continue; + } + aeskey = aesKeys.getOrDefault(column.getName(),null); + if(StringUtils.isEmpty(aeskey)){ + continue; + } + tableAl = tableMaps.get(column.getTable()); + if(!StringUtils.isEmpty(tableAl)){ + tableAl = tableAl+"."+column.getName(); + }else{ + tableAl = column.getName(); + } + sqlWhere = sqlWhere.replaceAll("\\b"+tableAl+"\\b","AES_DECRYPT(UNHEX("+tableAl+"),'"+aeskey+"')"); + } + + } + splicingSql.append(sqlWhere.toString()); + return splicingSql.toString(); + } + + /**鍒犻櫎鍔犲瘑鏁版嵁澶勭悊 + * @param sql sql璇彞 + * @param aesKeysTable aes绉橀挜 + * @return + */ + public static String deleteSql(String sql,Map<String,Map<String,String>> aesKeysTable){ + //瑁呰浇閲嶅啓鐨剆ql璇彞 + StringBuilder splicingSql = new StringBuilder(); + + //sql = SQLUtils.format(sql, JdbcConstants.MYSQL); + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement sqlStatement = parser.parseStatement(); + //鑾峰彇鏍煎紡鍖栫殑slq璇彞 + sql = sqlStatement.toString(); + + MySqlDeleteStatement deleteStatement = (MySqlDeleteStatement)sqlStatement; + + String insertName = deleteStatement.getTableName().getSimpleName(); + + String[] datas = sql.split("WHERE",2); + + Map<String,String> aesKeys = aesKeysTable.get(insertName); + if(aesKeys == null){ + return sql; + } + + splicingSql.append("DELETE FROM "+insertName); + + String aeskey = null; + + String sqlWhere = " WHERE"; + //鎶婂墿涓嬬殑鎷兼帴涓婃潵 + if(datas.length > 1){ + for(int i =1;i<datas.length;i++){ + sqlWhere = sqlWhere+datas[i]; + } + + parser = new MySqlStatementParser("SELECT * FROM "+insertName+" "+sqlWhere); + sqlStatement = parser.parseStatement(); + + ExportTableAliasVisitor visitorTable = new ExportTableAliasVisitor(); + sqlStatement.accept(visitorTable); + + //鑾峰彇琛ㄥ拰鍒悕 + Map<String,String> tableMaps = visitorTable.getTableMap(); + tableMaps.put(insertName,null); + + //鑾峰彇鎵�鏈夌殑瀛楁 + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + sqlStatement.accept(visitor); + + String tableAl = null; + //閬嶅巻鎵�鏈夊瓧娈� + Collection<TableStat.Column> columns= visitor.getColumns(); + for(TableStat.Column column:columns){ + + aesKeys= aesKeysTable.get(column.getTable()); + if(aesKeys == null){ + continue; + } + aeskey = aesKeys.getOrDefault(column.getName(),null); + if(StringUtils.isEmpty(aeskey)){ + continue; + } + tableAl = tableMaps.get(column.getTable()); + if(!StringUtils.isEmpty(tableAl)){ + tableAl = tableAl+"."+column.getName(); + }else{ + tableAl = column.getName(); + } + sqlWhere = sqlWhere.replaceAll("\\b"+tableAl+"\\b","AES_DECRYPT(UNHEX("+tableAl+"),'"+aeskey+"')"); + } + + } + splicingSql.append(sqlWhere.toString()); + return splicingSql.toString(); + } + +} diff --git a/src/main/java/com/hx/mybatis/aes/springbean/VariableAesKey.java b/src/main/java/com/hx/mybatis/aes/springbean/VariableAesKey.java new file mode 100644 index 0000000..b9dba4c --- /dev/null +++ b/src/main/java/com/hx/mybatis/aes/springbean/VariableAesKey.java @@ -0,0 +1,289 @@ +package com.hx.mybatis.aes.springbean; + +import com.gitee.sunchenbin.mybatis.actable.annotation.Table; +import com.hx.common.annotations.MysqlHexAes; +import com.hx.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.JarURLConnection; +import java.net.URL; +import java.net.URLDecoder; +import java.util.*; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +/** + * 鑾峰彇鎸囧畾鍖呴噷闈㈢殑AES绉橀挜 + */ +@Component +public class VariableAesKey { + + //log4j鏃ュ織 + private static Logger logger = LoggerFactory.getLogger(VariableAesKey.class.getName()); + + @Resource + private ConstantBean constantBean; + + /**鏄惁宸茬粡鍚姩瀹�*/ + public static int isRun = 0; + + /**瀛樺偍鎵�鏈堿ES鐨勭閽�*/ + public static Map<String,String> aesKeys = new HashMap<>(); + /**鏍规嵁琛ㄦ槑鏉ュ瓨鍌ˋES绉橀挜*/ + public static Map<String,Map<String,String>> aesKeysTable = new HashMap<>(); + + /**鍥哄畾鐨刟es绉橀挜*/ + public static String AES_KEY = null; + + /**瀛樺偍AES绉橀挜*/ + public static void setAesKey(String aesKeyFild,String aesKey){ + aesKeys.put(aesKeyFild,aesKey); + } + /**鑾峰彇AES绉橀挜*/ + public static String getAesKey(String aesKeyFild){ + if(aesKeyFild == null){ + return AES_KEY; + } + if(StringUtils.isEmpty(aesKeys.get(aesKeyFild))){ + return AES_KEY; + }else { + return aesKeys.get(aesKeyFild); + } + } + + /** + * 椤圭洰鍚姩灏辨墽琛屽悗灏辨墽琛岃鏂规硶 + */ + @PostConstruct + public void VariableAesKey(){ + + isRun = 1; + //椤圭洰鍚姩鐨勬椂鍊欏~鍏� + logger.info("鎵弿鑾峰彇AES鐨勫寘:" + constantBean.getPackPath()); + AES_KEY = constantBean.getFixedAesKey(); + if(!StringUtils.isEmpty(constantBean.getPackPath())){ + Set<Class<?>> classes = classData(constantBean.getPackPath()); + logger.info("鎵弿鑾峰彇AES鐨勫寘classes:" + classes.size()); + Map<String,String> aesKeysFild = new HashMap<>(); + boolean isAes = false; + String tableName = null; + + for(Class<?> cl:classes){ + //琛ㄥ悕绉� + boolean hasAnnotation = cl.isAnnotationPresent(Table.class); + if(!hasAnnotation){ + continue; + } + Table table = cl.getAnnotation(Table.class); + tableName = table.name(); + + aesKeysFild = new HashMap<>(); + isAes = false; + + // 鍙栧緱鏈被鐨勫叏閮ㄥ睘鎬� + Field[] fields = cl.getDeclaredFields(); + fields = getPatentFields(fields,cl); + for (Field field:fields) { + // 鍒ゆ柇鏂规硶涓槸鍚︽湁鎸囧畾娉ㄨВ绫诲瀷鐨勬敞瑙� + hasAnnotation = field.isAnnotationPresent(MysqlHexAes.class); + if (hasAnnotation) { + // 鏍规嵁娉ㄨВ绫诲瀷杩斿洖鏂规硶鐨勬寚瀹氱被鍨嬫敞瑙� + MysqlHexAes mysqlHexAes = field.getAnnotation(MysqlHexAes.class); + + //String aesKeyField = mysqlHexAes.aesKeyField(); + String aesKey = mysqlHexAes.aesKey(); + + if(StringUtils.isEmpty(aesKey)){ + aesKey = constantBean.getFixedAesKey(); + if(StringUtils.isEmpty(aesKey)){ + throw new RuntimeException("mysql鐨凙ES绉橀挜涓嶈兘涓虹┖:"+field.getName()); + } + } + String key = aesKeys.get(field.getName()); + if(StringUtils.isEmpty(key)){ + aesKeys.put(field.getName(),aesKey); + aesKeysFild.put(field.getName(),aesKey); + isAes = true; + }else{ + isAes = true; + aesKeysFild.put(field.getName(),aesKey); + if(!aesKey.equals(key)){ + throw new RuntimeException("瀛楁/瀹氫箟鐨凙ES绉橀挜瀛楁銆�"+field.getName()+"銆戝涓竴鏍凤紝浣嗘槸AES绉橀挜涓嶄竴鏍�"); + } + } + } + } + if(isAes){ + aesKeysTable.put(tableName,aesKeysFild); + } + } + } + } + + /**鑾峰彇鍖呬笅闈㈢殑鎵�鏈夋枃浠�*/ + public static Set<Class<?>> classData(String packPath){ + Set<Class<?>> classes = new LinkedHashSet(); + String[] split = packPath.split(",|;"); + String[] var3 = split; + int var4 = split.length; + + label82: + for(int var5 = 0; var5 < var4; ++var5) { + String pack = var3[var5]; + boolean recursive = true; + String packageName = pack; + String packageDirName = pack.replace('.', '/'); + + try { + Enumeration dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); + + while(true) { + label75: + while(true) { + if (!dirs.hasMoreElements()) { + continue label82; + } + + URL url = (URL)dirs.nextElement(); + String protocol = url.getProtocol(); + if ("file".equals(protocol)) { + System.err.println("file绫诲瀷鐨勬壂鎻�:" + pack); + String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); + findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes); + } else if ("jar".equals(protocol)) { + System.err.println("jar绫诲瀷鐨勬壂鎻�"); + + try { + JarFile jar = ((JarURLConnection)url.openConnection()).getJarFile(); + Enumeration entries = jar.entries(); + + while(true) { + JarEntry entry; + String name; + int idx; + do { + do { + if (!entries.hasMoreElements()) { + continue label75; + } + + entry = (JarEntry)entries.nextElement(); + name = entry.getName(); + if (name.charAt(0) == '/') { + name = name.substring(1); + } + } while(!name.startsWith(packageDirName)); + + idx = name.lastIndexOf(47); + if (idx != -1) { + packageName = name.substring(0, idx).replace('/', '.'); + } + } while(idx == -1 && !recursive); + + if (name.endsWith(".class") && !entry.isDirectory()) { + String className = name.substring(packageName.length() + 1, name.length() - 6); + + try { + classes.add(Class.forName(packageName + '.' + className)); + } catch (ClassNotFoundException var20) { + var20.printStackTrace(); + } + } + } + } catch (IOException var21) { + var21.printStackTrace(); + } + } + } + } + } catch (IOException var22) { + var22.printStackTrace(); + } + } + + return classes; + } + + /** + * 浠ユ枃浠剁殑褰㈠紡鏉ヨ幏鍙栧寘涓嬬殑鎵�鏈塁lass + * + * @param packageName + * @param packagePath + * @param recursive + * @param classes + */ + public static void findAndAddClassesInPackageByFile( + String packageName, + String packagePath, + final boolean recursive, + Set<Class<?>> classes){ + // 鑾峰彇姝ゅ寘鐨勭洰褰� 寤虹珛涓�涓狥ile + File dir = new File(packagePath); + // 濡傛灉涓嶅瓨鍦ㄦ垨鑰� 涔熶笉鏄洰褰曞氨鐩存帴杩斿洖 + if (!dir.exists() || !dir.isDirectory()) { + // log.warn("鐢ㄦ埛瀹氫箟鍖呭悕 " + packageName + " 涓嬫病鏈変换浣曟枃浠�"); + return; + } + // 濡傛灉瀛樺湪 灏辫幏鍙栧寘涓嬬殑鎵�鏈夋枃浠� 鍖呮嫭鐩綍 + File[] dirfiles = dir.listFiles(new FileFilter(){ + // 鑷畾涔夎繃婊よ鍒� 濡傛灉鍙互寰幆(鍖呭惈瀛愮洰褰�) 鎴栧垯鏄互.class缁撳熬鐨勬枃浠�(缂栬瘧濂界殑java绫绘枃浠�) + @Override + public boolean accept(File file){ + return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); + } + }); + // 寰幆鎵�鏈夋枃浠� + for (File file : dirfiles){ + // 濡傛灉鏄洰褰� 鍒欑户缁壂鎻� + if (file.isDirectory()) { + findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); + }else{ + // 濡傛灉鏄痡ava绫绘枃浠� 鍘绘帀鍚庨潰鐨�.class 鍙暀涓嬬被鍚� + String className = file.getName().substring(0, file.getName().length() - 6); + try{ + // 娣诲姞鍒伴泦鍚堜腑鍘� + // classes.add(Class.forName(packageName + '.' + + // className)); + // 缁忚繃鍥炲鍚屽鐨勬彁閱掞紝杩欓噷鐢╢orName鏈変竴浜涗笉濂斤紝浼氳Е鍙憇tatic鏂规硶锛屾病鏈変娇鐢╟lassLoader鐨刲oad骞插噣 + classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className)); + }catch (ClassNotFoundException e){ + // log.error("娣诲姞鐢ㄦ埛鑷畾涔夎鍥剧被閿欒 鎵句笉鍒版绫荤殑.class鏂囦欢"); + e.printStackTrace(); + } + } + } + } + + /** + * 鑾峰彇鐖剁被鐨勫瓧娈� + * @param fields + * @param clas + * @return + */ + public static Field[] getPatentFields(Field[] fields,Class<?> clas){ + if (clas.getSuperclass() != null) { + Class clsSup = clas.getSuperclass(); + List<Field> fieldList = new ArrayList<Field>(); + fieldList.addAll(Arrays.asList(fields)); + fieldList.addAll(Arrays.asList(clsSup.getDeclaredFields())); + fields = new Field[fieldList.size()]; + int i = 0; + for (Object field : fieldList.toArray()) { + fields[i] = (Field) field; + i++; + } + fields = getPatentFields(fields,clsSup); + } + return fields; + } + + +} diff --git a/src/main/java/com/hx/util/mysql/aes/MysqlHexAes.java b/src/main/java/com/hx/util/mysql/aes/MysqlHexAesTool.java similarity index 98% rename from src/main/java/com/hx/util/mysql/aes/MysqlHexAes.java rename to src/main/java/com/hx/util/mysql/aes/MysqlHexAesTool.java index c2a5d0a..8ac6a9c 100644 --- a/src/main/java/com/hx/util/mysql/aes/MysqlHexAes.java +++ b/src/main/java/com/hx/util/mysql/aes/MysqlHexAesTool.java @@ -14,7 +14,7 @@ * @author CJH * @Date 2021-01-06 */ -public class MysqlHexAes { +public class MysqlHexAesTool { public static SecretKeySpec generateMySQLAESKey(final String key, final String encoding) { -- Gitblit v1.8.0