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/VariableAesKey.java |  289 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 289 insertions(+), 0 deletions(-)

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;
+    }
+
+
+}

--
Gitblit v1.8.0