Loading Encrypted JarFile Via URLCassloader

。_饼干妹妹 提交于 2019-12-09 13:59:38

问题


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:


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.



来源:https://stackoverflow.com/questions/13965095/loading-encrypted-jarfile-via-urlcassloader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!