tomcat WebappClassLoader 加密class文件

对class文件时行加密,tomcat加载class文件时再进行解密.可以达到隐藏代码的目的.下面用commons-codec中的base64对class进行encode,再在tomcat加载时对class进行decode.
1.对要encode的class进行编码:
public static void main(String[] args) throws IOException {
FileInputStream file = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
file = new FileInputStream(
"./target/classes/kevin/ClassLoader.class");
bis = new BufferedInputStream(file);
byte[] b = new byte[bis.available()];
bis.read(b);
byte[] encodeB = Base64.encodeBase64(b);

fos = new FileOutputStream("ClassLoader.class");
bos = new BufferedOutputStream(fos);
bos.write(encodeB);
bos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
file.close();
bis.close();
fos.close();
bos.close();
}
}
2.将生成的class放入部署好的工程相应位置.
3.到tomcat.apache.org下载tomcat的源代码.
4.将eclipse.classpath, eclipse.project修改成.classpath, .project后,直接用eclipse导入工程apache-tomcat-6.0.32-src,再导入缺少的包.
5.在工程apache-tomcat-6.0.32-src中找到org.apache.catalina.loader.WebappClassLoader文件,再找到protected Class findClassInternal(String name) throws ClassNotFoundException 方法,将内容:
clazz = defineClass(name, entry.binaryContent, 0,
entry.binaryContent.length, new CodeSource(
entry.codeBase, entry.certificates));
修改为:
if (name.indexOf("ClassLoader") >= 0) {
byte[] base64Array = entry.binaryContent;
byte[] orginByteArray = Base64.decodeBase64(base64Array);
clazz = defineClass(name, orginByteArray, 0,
orginByteArray.length, new CodeSource(
entry.codeBase, entry.certificates));
} else {
clazz = defineClass(name, entry.binaryContent, 0,
entry.binaryContent.length, new CodeSource(
entry.codeBase, entry.certificates));
}
6.编译完成后,将WebappClassLoader.class及其子类文件替换运行时的tomcat/lib下的catalina.jar包中相同文件.
7.当tomcat运行需加载ClassLoader.class时,将会先对其进行decode,达到加密的目的.

猜你喜欢

转载自qingwei201314.iteye.com/blog/1130678