Class Loader Example: Load Class "By Hand" to "Unrotate" Bytes
Java Source
// Apply (for example) as follows:
// java ReflectionTest Hello 1
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 ReflectionTest {
public static void main (String a[]) {
try {
int key = Integer.parseInt(a[1]);
String classname = a[0];
// ----------------------------------
// Class cl = Class.forName(classname); // Can't use this - must use next two lines
// ----------------------------------
CryptClassLoader loader = new CryptClassLoader(classname, key);
Class cl = loader.returnClass();
//-----------------------------------------------------------------------------------------
// Next two lines could be used here instead of following four
// ----------------------------------------------------------
// Method m = cl.getMethod("sayHello", null); // Class[] { } not needed
// m.invoke(null, null); // Hello obj, Object[] { } not needed (static method and no args)
//-----------------------------------------------------------------------------------------
Constructor ct = cl.getConstructor ( null );
Object obj = ct.newInstance ( null );
Method m = cl.getMethod("sayHello", null); // Class[] { } not needed
m.invoke(obj, null); // Object[] { } not needed (no args to method)
}
catch (Exception e) {
System.out.println(e);
}
}
}