您的位置:首页 > 职场人生

黑马程序员_java加密类与classLoader

2013-01-26 15:41 423 查看
------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------

目的:写一个类,加密此类,写一个类加载器加载加密后的类运行

用于测试的类:

public class Test {

@Override

public String toString() {
return "itheima";

}

}

编译后将Test.class复制到D:\myclass中

写一个类MyCalssLoader继承ClassLoader

在类中写一个用于加密和解密的函数cypher:

public static void cypher(InputStream ips, OutputStream ops)
throws IOException {
int b = 0;
while ((b = ips.read()) != -1) {
ops.write(b ^ 0xff);
}
}

将Test.class加密

在main中执行以下代码

String srcPath="d:\\myclass\\Test.class";
String destPath="d:\\myclass\\Test2.class";
FileInputStream fis = new FileInputStream(new File(srcPath));
FileOutputStream fos = new FileOutputStream(new File(destPath));
cypher(fis, fos);
fis.close();
fos.close();

这样就得到一个加密了的Test类名称为Test2.calss

将以上main中的代码注释掉不用再运行

在MyClassLoader中重写findClass函数

@SuppressWarnings("deprecation")
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String className=name;
byte[] bytes;
try {
File file = new File(className);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
cypher(fis, bos);
fis.close();
bytes = bos.toByteArray();
bos.close();
//System.out.println(bytes.length);
Class<?> clazz = null;
try {
clazz = defineClass(bytes, 0, bytes.length);
if (clazz != null)
return clazz;
} catch (ClassFormatError e) {
System.out.println("类格式错误"+e);
}
} catch (IOException e1) {
System.out.println("IO错误"+e1);
}
return super.findClass(name);
}

再写上构造函数

public MyClassLoader() {
}//为求简便不写带参数的

这样MyClassLoader就写完了

然后写一个类ClassLoaderTest运行刚才加密的类Test2.class

在主函数中写上代码

String className="d:\\myclass\\Test2.class";
Class<?> clazz1=new MyClassLoader().loadClass(className);
System.out.println(clazz1.newInstance().toString()+"测试加密的类");

结果输出

itheima测试加密的类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息