您的位置:首页 > 其它

简单的class文件加密解密

2016-12-19 11:23 417 查看
加密生成的class文件

package com.dasenlin.encrpt;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
* 测试取反操作
* @author Administrator
*
*/
public class EncriptUtil {

/**
* @param args
*/
public static void main(String[] args) {
encrpt("E:/LearnJavaProjectText/myjava/HelloWorld.class","E:/LearnJavaProjectText/mytemp/HelloWorld.class");
}
/**
* 测试的是取反
* @param src
* @param dest
*/
public static void encrpt(String src,String dest){
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis = new FileInputStream(src);
fos = new FileOutputStream(dest);
int temp =-1;
while((temp=fis.read())!=-1){
fos.write(temp^0xff);//读出的数据进行取反;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(null!=fis){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

}


解密加密后的class文件的类加载器

package com.dasenlin.encrpt;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
* 解密的类加载器
* @author Administrator
*
*/
public class DecriptClassLoader extends ClassLoader {
private String rootDir;

public DecriptClassLoader(String rootDir){
this.rootDir=rootDir;
}

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
Class<?> c = findLoadedClass(name);
if(c!=null){
return c;
}else{
ClassLoader parent=this.getParent();
try {
c=parent.loadClass(name);
} catch (Exception e) {
//e.printStackTrace();
}    //双亲委托机制,委派给父类加载。
if(c!=null){
return c;
}else{
byte[]classData = getClassData(name);
if(classData==null){
throw new ClassNotFoundException();
}else{
c=defineClass(name,classData,0,classData.length);
}
}
}
return c;
}

private byte[] getClassData(String name) {
String path=rootDir+"/"+name.replace('.', '/')+".class";
InputStream is =null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
is=new FileInputStream(path);
int temp =-1;
while((temp=is.read())!=-1){
baos.write(temp^0xff);//读出的数据进行取反;
}
return baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
}finally{
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}


测试

package com.dasenlin.encrpt;
/**
* 通过自定义的解密类加载器加载
* @author Administrator
*
*/
public class DemoLoad {

/**
* @param args
*/
public static void main(String[] args) {
DecriptClassLoader loader = new DecriptClassLoader("E:/LearnJavaProjectText/mytemp/");
try {
Class<?> c =loader.loadClass("HelloWorld");
System.out.println(c);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

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