服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

深入讨论java字节码加密技术(1)


  如果把的class文件加密,在运行时用指定的类加载器(class loader)装入并解密它,能防止被反编译吗?结论是防止java字节码反编译这个问题在java语言雏形期就有了,尽管市面上存在一些反编译的工具可以利用,但是java程序员还是不断的努力寻找新的更有效的方法来保护他们的智慧结晶。在此,我将详细给大家解释这一直来在论坛上有争议的话题。
  
    class文件能被很轻松的重构生成java源文件与最初java字节码的设计目的和商业交易有紧密地联系。另外,java字节码被设计成简洁、平台独立性、网络灵活性,并且易于被字节码解释器和jit (just-in-time)/hotspot 编译器所分析。可以清楚地了解程序员的目的, class文件要比java源文件更易于分析。
  
    如果不能阻止被反编译的话,至少可以通过一些方法来增加它的困难性。例如: 在一个分步编译里,你可以打乱class文件的数据以使其难读或者难以被反编译成正确的java源文件,前者可以采用极端函数重载,后者用操作控制流建立控制结构使其难以恢复正常次序。有更多成功的商业困惑者采用这些或其他的技术来保护自己的代码。
  
    不幸的是,哪种方法都必须改变jvm运行的代码,并且许多用户害怕这种转化会给他们的程序带来新的bug。而且,方法和字段重命名会调用反射从而使程序停止工作,改变类和包的名字会破坏其他的java apis(jndi, url providers, etc),除了改变名字,如果字节码偏移量和源代码行数之间的关系改变了,在恢复这有异常的堆栈将很困难。于是就有了一些打乱java源代码的选项,但是这将从本质上导致一系列问题的产生。
  
    加密而不打乱
  
    或许上述可能会使你问,假如我把字节码加密而不是处理字节码,并且jvm运行时自动将它解密并装入类加载器,然后jvm运行解密后的字节码文件,这样就不会被反编译了对吗?考虑到你是第一个提出这种想法的并且它又能正常运行,我表示遗憾和不幸,这种想法是错误的。
  
    下面是一个简单的类编码器:为了阐明这种思想,我采用了一个实例和一个很通用的类加载器来运行它,该程序包括两个类:
  
  public class main
  {
   public static void main (final string [] args)
   {
   system.out.println ("secret result = " +
   mysecretclass.mysecretalgorithm ());
   }
  
  } // end of class
  
  
  package my.secret.code;
  import java.util.random;
  
  public class mysecretclass
  {
   /**
   * guess what, the secret algorithm just uses
   * a random number generator...
   */
   public static int mysecretalgorithm ()
   {
   return (int) s_random.nextint ();
   }
  
   private static final random s_random = new random
   (system.currenttimemillis ());
  
  } // end of class
  
  
  
    我想通过加密相关的class文件并在运行期解密来隐藏my.secret.code.mysecretclass的执行。用下面这个工具可以达到效果(你可以到这里下载resources):
  
  public class encryptedclassloader extends urlclassloader
  {
   public static void main (final string [] args)
   throws exception
   {
   if ("-run".equals (args [0]) && (args.length >= 3))
   {
   // create a custom loader that will use the current
   //loader as delegation parent:
   final classloader apploader =
   new encryptedclassloader (encryptedclassloader.
   class.getclassloader (),
   new file (args [1]));
  
   // thread context loader must be adjusted as well:
   thread.currentthread ().setcontextclassloader
   (apploader);
  
   final class app = apploader.loadclass (args [2]);
  
   final method appmain = app.getmethod ("main",
   new class [] {string [].class});
   final string [] appargs = new string[args.length -3];
   system.arraycopy (args,3,appargs,0,appargs.length);
  
   appmain.invoke (null, new object [] {appargs});
   }
   else if ("-encrypt".equals(args[0])&&(args.length>=3))
   {
   ... encrypt specified classes ...
   }
   else
   throw new illegalargumentexception (usage);
   }
  
   /**
   * overrides java.lang.classloader.loadclass() to change
   * the usual parent-child delegation rules just enough to
   * be able to "snatch" application classesfrom under
   * system classloader's nose.
   */
   public class loadclass (final string name,
   final boolean resolve)
   throws classnotfoundexception
   {
   if (trace) system.out.println ("loadclass (" + name +
   ", " + resolve + ")");
   class c = null;
  
   // first, check if this class has already been defined
   // by this classloader instance:
   c = findloadedclass (name);
  
   if (c == null)
   {
   class parentsversion = null;
   try
   {
   // this is slightly unorthodox: do a trial load via the
   // parent loader and note whether the parent delegated or not;
   // what this accomplishes is proper delegation for all core
   // and extension classes without my having to filter
   // on class name:
   parentsversion = getparent ().loadclass (name);
  
   if(parentsversion.getclassloader()!=getparent())
   c = parentsversion;
   }
   catch (classnotfoundexception ignore) {}
   catch (classformaterror ignore) {}
  
   if (c == null)
   {
   try
   {
   // ok, either 'c' was loaded by the system (not the bootstrap
   // or extension) loader (in which case i want to ignore that
   // definition) or the parent failed altogether; either way i
   // attempt to define my own version:
   c = findclass (name);
   }
   catch (classnotfoundexception ignore)
   {
   // if that failed, fall back on the parent's version
   // [which could be null at this point]:
   c = parentsversion;
   }
   }
   }
  
   if (c == null)
   throw new classnotfoundexception (name);
  
   if (resolve)
   resolveclass (c);
  
   return c;
   }
  
   /**
   * overrides java.new.urlclassloader.defineclass() to
   * be able to call crypt() before defining a class.
   */
   protected class findclass (final string name)
   throws classnotfoundexception
   {
   if(trace) system.out.println("findclass(" + name + ")");
  
   //.class files are not guaranteed to be loadable as resources;
   // but if sun's code does it, so perhaps can mine...
   final string classresource = name.replace
   ('.', '/') + ".class";
   final url classurl = getresource (classresource);
  
   if (classurl == null)
   throw new classnotfoundexception (name);
   else
   {
   inputstream in = null;
   try
   {
   in = classurl.openstream ();
  
   final byte [] classbytes = readfully (in);
  
   // "decrypt":
   crypt (classbytes);
   if (trace) system.out.println ("decrypted
   [" +

扫描关注微信公众号