Java实现自定义classLoader动态解密class文件


前言

要实现classLoader动态解密class文件,就必须先了解Java的类加载机制、了解双亲委托机制。然后自定义一个classLoader,继承于classLoader。

文章中引用到上一篇文章中的解密方法(edCipher.decryptClass(name)),详情请移步至:Java加解密Class文件

代码实现

 1 /**
 2  * 动态加载类
 3  */
 4 public class EdClassLoader extends ClassLoader {
 5 
 6     private String toolFile = "com.pub.Secretive";
 7 
 8     private EdCipher edCipher = new EdCipher();
 9 
10     public EdClassLoader() {
11         super(Thread.currentThread().getContextClassLoader());
12     }
13 
14     @Override
15     protected Class<?> findClass(String name) throws ClassNotFoundException {
16         EdCipher edCipher = this.edCipher == null ? new EdCipher() : this.edCipher;
17         byte[] data = edCipher.decryptClass(name);
18         int length = data == null ? 0 : data.length;
19         return defineClass(toolFile, data, 0, length);
20     }
21 
22     @Override
23     public Class<?> loadClass(String s) throws ClassNotFoundException {
24         if (!s.contains("Checker")) {
25             Class loadedClass = findLoadedClass(s);
26             if (loadedClass == null) {
27                 loadedClass = getParent().loadClass(s);
28                 return loadedClass;
29             } else {
30                 return loadedClass;
31             }
32         }
33         return findClass(s);
34     }
35 
36     /**
37     * 获取需要解密的类
38     */
39     public String getToolfile() {
40         return toolFile;
41     }
42 
43     //在动态加载class文件后,需要通过反射才能调用其中方法
44     public static void main(String[] args) throws ClassNotFoundException {
45          EdClassLoader edClassLoader = new EdClassLoader();
46         Object result = null;
47         try {
48             Class myClass = edClassLoader.loadClass(edClassLoader.getToolfile());
49             // method1 就是方法名
50             Method method = myClass.getDeclaredMethod("method1");
51             Object obj = myClass.newInstance();
52             // result 就是方法返回值
53             result = method.invoke(obj);
54         } catch (Exception e) {
55             e.printStackTrace();
56         }
57         System.out.println(result);
58     }
59 }

 

posted @ 2018-08-10 17:36  鲸落WhaleFall  阅读(2669)  评论(1编辑  收藏  举报