对jar或者war进行加密解密
whycxzp
2021-07-15 cfdf00d3357268fa6de56db849e40aeaf714cff3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.whyc;
 
import com.whyc.util.JarUtils;
import com.whyc.util.StrUtils;
 
import java.lang.instrument.ClassFileTransformer;
import java.security.ProtectionDomain;
 
 
/**
 * AgentTransformer
 * jvm加载class时回调
 *
 * @author perry
 */
public class AgentTransformer implements ClassFileTransformer {
    //密码
    private char[] pwd;
 
    /**
     * 构造方法
     *
     * @param pwd 密码
     */
    public AgentTransformer(char[] pwd) {
        this.pwd = pwd;
    }
 
    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                            ProtectionDomain domain, byte[] classBuffer) {
        if (className == null || domain == null || loader == null) {
            return classBuffer;
        }
 
        //获取类所在的项目运行路径
        String projectPath = domain.getCodeSource().getLocation().getPath();
        projectPath = JarUtils.getRootPath(projectPath);
        if (StrUtils.isEmpty(projectPath)) {
            return classBuffer;
        }
 
        className = className.replace("/", ".").replace("\\", ".");
 
        byte[] bytes = JarDecryptor.getInstance().doDecrypt(projectPath, className, this.pwd);
        //CAFEBABE,表示解密成功
        if (bytes != null && bytes[0] == -54 && bytes[1] == -2 && bytes[2] == -70 && bytes[3] == -66) {
            return bytes;
        }
        return classBuffer;
 
    }
}