|
| 1 | +package com.di1shuai.base.jvm.classloader; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * @author: shea |
| 7 | + * @date: 2021/7/29 |
| 8 | + * @description: classloader应用: |
| 9 | + * 加密classloader |
| 10 | + * <p> |
| 11 | + * x ^ y ^ y = x |
| 12 | + * 生成class文件后进行加密 |
| 13 | + * 使用解密的classloader进行读取 |
| 14 | + */ |
| 15 | +public class EncriptionClassLoader extends ClassLoader { |
| 16 | + |
| 17 | + |
| 18 | + private static final int seed = 0B10110110; |
| 19 | + |
| 20 | + private static final String basepath = "/Users/shea/Documents/GitRepo/mine/back-end/java-versions/java-8/target/classes/"; |
| 21 | +// String basepath = "/Users/shea/Documents/GitRepo/mine/back-end/java-versions/java-base/target/classes"; |
| 22 | + |
| 23 | + @Override |
| 24 | + protected Class<?> findClass(String name) throws ClassNotFoundException { |
| 25 | + System.out.println("======进入自定义ClassLoader - findClass ====="); |
| 26 | + File file = new File(basepath, name.replaceAll("\\.", "/").concat(".di1shuaiclass")); |
| 27 | + try { |
| 28 | + FileInputStream fileInputStream = new FileInputStream(file); |
| 29 | + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); |
| 30 | + int b = 0; |
| 31 | + while ((b = fileInputStream.read()) != -1) { |
| 32 | + byteArrayOutputStream.write(b ^ seed); |
| 33 | + } |
| 34 | + fileInputStream.close(); |
| 35 | + byteArrayOutputStream.close(); |
| 36 | + byte[] bytes = byteArrayOutputStream.toByteArray(); |
| 37 | + return defineClass(name, bytes, 0, bytes.length); |
| 38 | + } catch (Exception e) { |
| 39 | + e.printStackTrace(); |
| 40 | + } finally { |
| 41 | + System.out.println("======结束自定义ClassLoader - findClass====="); |
| 42 | + } |
| 43 | + return super.findClass(name); |
| 44 | + } |
| 45 | + |
| 46 | + |
| 47 | + public static void main(String[] args) throws Exception { |
| 48 | +// String className = "com.di1shuai.base.gc.HelloJVM"; |
| 49 | + String className = "com.diyishuai.java8.Student"; |
| 50 | + encFile(className); |
| 51 | + EncriptionClassLoader encriptionClassLoader = new EncriptionClassLoader(); |
| 52 | + Class<?> aClass = encriptionClassLoader.loadClass(className); |
| 53 | + System.out.println(aClass); |
| 54 | + } |
| 55 | + |
| 56 | + private static void encFile(String name) throws Exception { |
| 57 | + File file = new File(basepath, name.replaceAll("\\.", "/").concat(".class")); |
| 58 | + FileInputStream fileInputStream = new FileInputStream(file); |
| 59 | + FileOutputStream fileOutputStream = new FileOutputStream(new File(basepath, name.replaceAll("\\.", "/").concat(".di1shuaiclass"))); |
| 60 | + int b = 0; |
| 61 | + while ((b = fileInputStream.read()) != -1) { |
| 62 | + fileOutputStream.write(b ^ seed); |
| 63 | + } |
| 64 | + fileInputStream.close(); |
| 65 | + fileOutputStream.close(); |
| 66 | + } |
| 67 | + |
| 68 | + |
| 69 | +} |
0 commit comments