自定義淚價值器2——加密class文件 解密加載class文件

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("......");
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章