对一个二进制文件进行加密,令java的类加载器无法识别(不符合类文件结构)
- package cn.itcast.cl;
- import java.io.ByteArrayOutputStream;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.io.OutputStream;
- public class MyClassLoader extends ClassLoader{
- /**把源目录下的二进制文件加密,生成到itcastlib下
- * @param args
- * 源路径G:\Users\king\eclipsespace\classloader\bin\cn\itcast\loadedclass\Attachment.class
- * dest:itcastlib
- */
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- String srcPath = args[0];
- String destDir = args[1];
- FileInputStream fis = new FileInputStream(srcPath);
- String destFileName = srcPath.substring(srcPath.lastIndexOf('\\')+1);
- String destPath = destDir + "\\" + destFileName;
- FileOutputStream fos = new FileOutputStream(destPath);
- cypher(fis,fos);
- fis.close();
- fos.close();
- }
-
- //就异或一下而已,当然可以用更复杂的算法对二进制流进行加密
- private static void cypher(InputStream ips ,OutputStream ops) throws Exception{
- int b = -1;
- while((b=ips.read())!=-1){
- ops.write(b ^ 0xff);
- }
- }
- private String classDir;
- public MyClassLoader(){
-
- }
- public MyClassLoader(String classDir){
- this.classDir = classDir;
- }
- }
//被加载的类
- package cn.itcast.loadedclass;
- import java.util.Date;
- public class Attachment extends Date
- {
- public String toString(){
- return "hello,itcast";
- }
- }
- package cn.itcast.cl;
- import cn.itcast.loadedclass.Attachment;
- public class CLTest
- {
- /**
- * @param args
- */
- public static void main(String[] args)
- {
- System.out.println(CLTest.class.getClassLoader().getClass().getName());
- System.out.println("C++ bootstrap "+System.class.getClassLoader());
- System.out.println("xxx");
- ClassLoader loader = CLTest.class.getClassLoader();
- while(loader != null){
- System.out.println(loader.getClass().getName());
- loader = loader.getParent();
- }
- System.out.println("循环递归向上寻找: "+loader+"\n");
- System.out.println("这是还没把加密类替换原来的类,运行没出错");
- Attachment attachment= new Attachment();
- System.out.println(attachment.toString());
- }
- }
- sun.misc.Launcher$AppClassLoader
- C++ bootstrap null
- xxx
- sun.misc.Launcher$AppClassLoader
- sun.misc.Launcher$ExtClassLoader
- 循环递归向上寻找: null
- 这是还没把加密类替换原来的类,运行没出错
- hello,itcast
当我把生成的加密类,替换掉以后,一运行马上抛异常,因为加载器无法识别这些乱七八糟的魔数,这样的话就要自己写类加载器来加载了
Exception in thread "main" java.lang.ClassFormatError: Incompatible magic value 889275713 in class file cn/itcast/loadedclass/Attachment
at cn.itcast.cl.CLTest.main(CLTest.java:20)
阅读(1249) | 评论(0) | 转发(0) |