Loading Encrypted JarFile Via URLCassloader

2020-06-30 04:00发布

I've been writing a little system to dynamically load AES encrypted jar files. My code:

public static void main(String args[]) throws Exception {

String jar = "http://site.com/api/rsc/test.jar";
List<URL> urls = new ArrayList<URL>();
urls.add(getURL(jar));
URL jarurl = urls.get(0);

ObjectInputStream ois = new ObjectInputStream((new URL("http://site.com/api/rsc/key_1.txt").openStream()));
Object o = ois.readObject();
DESKeySpec ks = new DESKeySpec((byte[])o);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey key = skf.generateSecret(ks);

Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec((byte[]) ois.readObject()));
CipherInputStream cis = new CipherInputStream((jarurl.openStream()), c);

JarInputStream jis = new JarInputStream(cis);
String main = jis.getManifest().getMainAttributes().getValue("Main-Class");
String classpaths[] = jis.getManifest().getMainAttributes().getValue("Class-Path").split(" ");

for (String classpath: classpaths) {
    urls.add(getURL(classpath));
}

URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[0]));
Class<?> cls = loader.loadClass(main);
Thread.currentThread().setContextClassLoader(loader);
Method m = cls.getMethod("main", new Class[]{new String[0].getClass()});
m.invoke(null, new Object[]{args});

}

This works fine with just a plain InputStream, and I have been able to decrypt files and read contents with the Cipher code before. WHen I try to run a simple hello world application, this is the error it throws:

Exception in thread "main" java.lang.ClassNotFoundException: helloworld.Main
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at jarloader.JarLoader.main(JarLoader.java:63)

Am I missing something? Thanks for your time. =)

1条回答
你好瞎i
2楼-- · 2020-06-30 04:37

You are adding a url for your encrypted jar to the URLClassLoader. how do you expect the URLClassLoader to decrypt the jar when it loads it?

your best bet would be to implement a custom classloader. extend SecureClassLoader and implement the relevant methods. there's a basic example in the ClassLoader javadocs.

查看更多
登录 后发表回答