class文件加密和解密

        在代码开发过程中,有时候可能需要对一些涉密的代码做加密处理,这里针对class文件的加密和解密写了一个样例作为参考。首先是通过java虚拟机自带的base64加密算法对class文件进行加密,加密成一个字符串。然后再通过一个自定义的类加载器,对字符串进行解密解析成class文件,再加载做初始化。HelloClassLoader类中的长字符串就是Hello.class文件根据base64加密算法生成的一长串字符串。

package jvm;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Base64;
import java.util.Base64.Encoder;
/*
 * 加密class文件
 */
public class HelloWorld {
    public static void main(String args[]) {
    	byte[] buffer = null;
    	//获取当前路径,这里是java工程路径
    	String str = System.getProperty("user.dir");
    	String filepath = ".\\src\\jvm\\Hello.class";
    	try {
    		FileInputStream fis = new FileInputStream(filepath);
    		ByteArrayOutputStream bos = new ByteArrayOutputStream();
    		byte[] b = new byte[1024];
    		int n;
    		while((n = fis.read(b))!=-1) {
    			bos.write(b,0,n);
    		}
    		fis.close();
    		bos.close();
    		buffer = bos.toByteArray();
    	}catch(Exception e) {
    	   e.printStackTrace();	
    	}
    	Encoder encoder = Base64.getEncoder();
    	String value = encoder.encodeToString(buffer);
        System.out.println(value);
    	System.out.println("HelloWorld");
    }
}
package jvm;
import java.lang.InstantiationException;
import java.util.Base64;
/*
 * 自定义一个加载器,用来实现加载加密过的class文件
 */
public class HelloClassLoader extends ClassLoader{
  
	  public static void main(String args[]) {
		  try {
	         Object obj = new HelloClassLoader().findClass("jvm.Hello").newInstance();
	         System.out.println("success");
		 System.out.println("ssss");
		  }catch(ClassNotFoundException e){
			  e.printStackTrace();
		  }catch(IllegalAccessException e1) {
			  e1.printStackTrace();
		  }catch(InstantiationException e2){
			  e2.printStackTrace();
		  }
	  }
	  
	  @Override
	  public Class findClass(String name) throws ClassNotFoundException{
	  String helloBase64 = "yv66vgAAADQAHAoABgAOCQAPABAIABEKABIAEwcAFAcAFQEABjxpbml0PgEAAygpVgEABENvZGUBAA9MaW5lTnVtYmVyVGFibGUBAAg8Y2xpbml0PgEAClNvdXJjZUZpbGUBAApIZWxsby5qYXZhDAAHAAgHABYMABcAGAEAGEhlbGxvIGNsYXNzIGluaXRhaWxpemVkIQcAGQwAGgAbAQAJanZtL0hlbGxvAQAQamF2YS9sYW5nL09iamVjdAEAEGphdmEvbGFuZy9TeXN0ZW0BAANvdXQBABVMamF2YS9pby9QcmludFN0cmVhbTsBABNqYXZhL2lvL1ByaW50U3RyZWFtAQAHcHJpbnRsbgEAFShMamF2YS9sYW5nL1N0cmluZzspVgAhAAUABgAAAAAAAgABAAcACAABAAkAAAAdAAEAAQAAAAUqtwABsQAAAAEACgAAAAYAAQAAAAMACAALAAgAAQAJAAAAJQACAAAAAAAJsgACEgO2AASxAAAAAQAKAAAACgACAAAABQAIAAYAAQAMAAAAAgAN";
		  byte[] bytes = decode(helloBase64);
		  return defineClass(name,bytes,0,bytes.length);
	  }
	
	  public byte[] decode(String base64) {
		  return Base64.getDecoder().decode(base64);
	  }
}

你可能感兴趣的:(java,java,后端,java虚拟机)