package cn.itcast.cc.classloader; import java.io.*; import java.security.Key; import javax.crypto.*; public class MyClassLoader extends ClassLoader { private Key key = null; private String traninfo = null; public MyClassLoader(Key key, String traninfo) { this.key = key; this.traninfo = traninfo; } @Override @SuppressWarnings("unchecked") protected Class findClass(String name) throws ClassNotFoundException { // 獲取class解密后的字節(jié)碼 byte[] classBytes = null; try { classBytes = loadClassBytes(name); } catch (Exception e) { throw new ClassNotFoundException(name); } // 使用字節(jié)碼,實(shí)例類對(duì)象 String clname = name.substring(name.lastIndexOf("/") + 1, name .lastIndexOf(".")); Class cl = defineClass(clname, classBytes, 0, classBytes.length); if (cl == null) throw new ClassNotFoundException(name); return cl; } private byte[] loadClassBytes(String name) throws IOException { // 讀入文件 FileInputStream ins = null; ByteArrayOutputStream baos = null; CipherInputStream cis = null; byte[] result = null; try { ins = new FileInputStream(name); Cipher cip = Cipher.getInstance(this.traninfo); cip.init(Cipher.DECRYPT_MODE, this.key); // 使用密碼解密class文件 cis = new CipherInputStream(ins, cip); baos = new ByteArrayOutputStream(); int len = 0; byte[] buf = new byte[1024]; while ((len = cis.read(buf)) != -1) { baos.write(buf, 0, len); } result = baos.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { // 釋放流 baos.close(); cis.close(); ins.close(); } return result; } } |