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 @   鲸落WhaleFall  阅读(2696)  评论(1编辑  收藏  举报
编辑推荐:
· 如果单表数据量大,只能考虑分库分表吗?
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
· 电商平台中订单未支付过期如何实现自动关单?
· 用 .NET NativeAOT 构建完全 distroless 的静态链接应用
· 为什么构造函数需要尽可能的简单
阅读排行:
· C# 多项目打包时如何将项目引用转为包依赖
· 如果单表数据量大,只能考虑分库分表吗?
· 一款让 Everything 更加如虎添翼的 .NET 开源辅助工具!
· 冲压车间软件实施
· (原创)[开源][.Net Framework 4.5] SimpleMVVM(极简MVVM框架)更
点击右上角即可分享
微信分享提示