码迷,mamicode.com
首页 > 其他好文 > 详细

自定义泪价值器2——加密class文件 解密加载class文件

时间:2014-08-01 23:21:12      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:类加载器

public class MyClassLoader extends ClassLoader {

	private String classDir;//自定义类加载器 所查找的目录
	MyClassLoader(String classDir){
		this.classDir = classDir;
	}

	@Override@SuppressWarnings("deprecation")
	//findClass的主要作用就是 把class文件读取到内存中 那么涉及两个流,,但是class文件被加密 所以需要先解密 然后写入内存
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		
		String classPath = classDir+"\\"+name+".class";
		System.out.println(classPath);
		try {
			System.out.println("我的类加载器");
			//读取class文件的流
			FileInputStream in = new FileInputStream(classPath);
			//将class文件的二进制数据 写入内存的流  之前要先解密
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			//解密 
			encryption(in, bout);
			in.close();
			byte[] buf = bout.toByteArray();
			return defineClass(buf, 0, buf.length);//将一个 byte 数组转换为 Class 类的实例
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();;
		}
		return super.findClass(name);
	}
	
	
	public static void main(String[] args) throws Exception {
		//源class文件路径
//		String srcPath = args[0];
		String srcPath = "bin/类加载器/testClass.class";
		File src = new File(srcPath);
//		String desDir = args[1];//加密后的class文件存放的目录
		String desDir = "bin/333";
		//读取指定文件
		FileInputStream in = new FileInputStream(src);
		String desPath = desDir+"\\"+src.getName();
		//class文件加密
		OutputStream out = new FileOutputStream(desPath);
		encryption(in,out);
		System.out.println("class文件加密成功");
		
	}
	//文件加密代码  从字节输入流in获取文件 进过加密 将数据 写入到输出流    注意  这里不要思维定势 认为 将数据写入OutputStream输出流就是写入文件
	private static void encryption(InputStream in,OutputStream out) throws Exception {
		// TODO Auto-generated method stub
		int i = -1;
		while ((i=in.read())!=-1) {
			out.write(i^0xfff);//将加密的字节数据写入到out流中
//			out.write(i);//不加密
		}
		System.out.println("......");
	}
}


本文出自 “要么拼命,要么滚回去!” 博客,请务必保留此出处http://jiangzuun2014.blog.51cto.com/8732469/1533982

自定义泪价值器2——加密class文件 解密加载class文件,布布扣,bubuko.com

自定义泪价值器2——加密class文件 解密加载class文件

标签:类加载器

原文地址:http://jiangzuun2014.blog.51cto.com/8732469/1533982

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!