Class Encryption: Decrypting and loading

Previous      Next      Java Source

import java.io.*;
import java.lang.reflect.*;

class CryptClassLoader extends ClassLoader {
   Class cls;
   
   public Class returnClass () {
      return cls;
   }

   public CryptClassLoader (String classname, int key) {
      try {
         FileInputStream in = new FileInputStream (classname+".class");
         ByteArrayOutputStream buffer = new ByteArrayOutputStream();
         int ch;
         while ((ch = in.read()) != -1) {
            buffer.write((ch + (256 - key)) % 256);
         }
         byte [] rec = buffer.toByteArray();
         cls = defineClass (classname, rec, 0, rec.length);
      }
      catch (Exception e) {
         System.out.println("File not found "+e);
      }
   }
}

public class ClassLoaderTest {
   public static void main (String a[]) {
      try {
         // ----------------------------------
         //   Class cl = Class.forName(a[0]);   
         // ----------------------------------
         int key = Integer.parseInt(a[1]);
         String classname = a[0];
         CryptClassLoader loader = new CryptClassLoader(classname, key);
         Class cl = loader.returnClass();
         Method m = cl.getMethod("sayHello", new Class[] { });
         m.invoke(null, null);
      }
      catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Usage: java ClassLoaderTest encrypted_class_file key");
      }
      catch (Exception e) {
         System.out.println(e);
      }
   }
}