大家知道,编译后的class文件如果不经过特殊处理,很容易被人反编译。
本文只是一个简单的例子。对class文件进行简单的加密。通过自定义的classload解密该class文件,
自定义一个classload:
import java.io.File; public class FileSystemClassLoader extends ClassLoader{ private String rootDir; public FileSystemClassLoader(String string){ this.rootDir=string; } protected Class<?> findClass(String name) throws ClassNotFoundException { byte[] classData = getClassData(name); if (classData == null) { throw new ClassNotFoundException(); } else { return defineClass(name, classData, 0, classData.length); } } private byte[] getClassData(String className) { String path = classNameToPath(className); try { InputStream ins = new FileInputStream(path); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; int bytesNumRead = 0; while ((bytesNumRead = ins.read(buffer)) != -1) { baos.write(buffer, 0, bytesNumRead); } return baos.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return null; } private String classNameToPath(String className){ System.out.println("OK!"); return rootDir+File.separatorChar+className.replace('.',File.separatorChar)+".class"; } }
测试的类文件;
public class myLoadClassTest { private String names; private String addrs; public String getName() { return names; } public void setName(String name) { this.names = name; } public String getAddr() { return addrs; } public void setAddr(String addr) { this.addrs = addr; } @Override public String toString() { return "myLoadClassTest{" + "name='" + names + '\'' + ", addr='" + addrs + '\'' + '}'; } }
import java.lang.reflect.Field; public class myTest { public static void main(String[] args) { // TODO Auto-generated method stub FileSystemClassLoader fileSystemClassLoader=new FileSystemClassLoader("url"); try { Class<?> clazz= fileSystemClassLoader.loadClass("com.xxx.xxx.xxx.myLoadClassTest"); fileSystemClassLoader.clearAssertionStatus(); Field[] files=clazz.getDeclaredFields(); System.out.println(files[0].getName()); System.out.println(clazz); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
相关的知识可以参考以下链接:
http://www.ibm.com/developerworks/cn/java/j-lo-classloader/#download
http://blog.csdn.net/aspdao/article/details/5309350