Java 反编译工具的使用与对比分析(一)

简介: Java 反编译工具的使用与对比分析

前言

Java 反编译,一听可能觉得高深莫测,其实反编译并不是什么特别高级的操作,Java 对于 Class 字节码文件的生成有着严格的要求,如果你非常熟悉 Java 虚拟机规范,了解 Class 字节码文件中一些字节的作用,那么理解反编译的原理并不是什么问题。甚至像下面这样的 Class 文件你都能看懂一二。

微信图片_20220414170931.jpg

一般在逆向研究和代码分析中,反编译用到的比较多。不过在日常开发中,有时候只是简单的看一下所用依赖类的反编译,也是十分重要的。

恰好最近工作中也需要用到 Java 反编译,所以这篇文章介绍目前常见的的几种 Java 反编译工具的使用,在文章的最后也会通过编译速度语法支持以及代码可读性三个维度,对它们进行测试,分析几款工具的优缺点

Procyon

Github 链接:https://github.com/mstrobel/procyon

Procyon不仅仅是反编译工具,它其实是专注于 Java 代码的生成和分析的一整套的 Java 元编程工具。主要包括下面几个部分:

  • Core Framework
  • Reflection Framework
  • Expressions Framework
  • Compiler Toolset (Experimental)
  • Java Decompiler (Experimental)

可以看到反编译只是 Procyon 的其中一个模块,Procyon 原来托管于 bitbucket,后来迁移到了 GitHub,根据 GitHub 的提交记录来看,也有将近两年没有更新了。不过也有依赖 Procyon 的其他的开源反编译工具如** decompiler-procyon**,更新频率还是很高的,下面也会选择这个工具进行反编译测试。

使用 Procyon

<!-- https://mvnrepository.com/artifact/org.jboss.windup.decompiler/decompiler-procyon -->
<dependency>
    <groupId>org.jboss.windup.decompiler</groupId>
    <artifactId>decompiler-procyon</artifactId>
    <version>5.1.4.Final</version>
</dependency>

写一个简单的反编译测试。

package com.wdbyte.decompiler;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import org.jboss.windup.decompiler.api.DecompilationFailure;
import org.jboss.windup.decompiler.api.DecompilationListener;
import org.jboss.windup.decompiler.api.DecompilationResult;
import org.jboss.windup.decompiler.api.Decompiler;
import org.jboss.windup.decompiler.procyon.ProcyonDecompiler;
/**
 * Procyon 反编译测试
 *
 *  @author https://github.com/niumoo
 * @date 2021/05/15
 */
public class ProcyonTest {
    public static void main(String[] args) throws IOException {
        Long time = procyon("decompiler.jar", "procyon_output_jar");
        System.out.println(String.format("decompiler time: %dms", time));
    }
    public static Long procyon(String source,String targetPath) throws IOException {
        long start = System.currentTimeMillis();
        Path outDir = Paths.get(targetPath);
        Path archive = Paths.get(source);
        Decompiler dec = new ProcyonDecompiler();
        DecompilationResult res = dec.decompileArchive(archive, outDir, new DecompilationListener() {
            public void decompilationProcessComplete() {
                System.out.println("decompilationProcessComplete");
            }
            public void decompilationFailed(List<String> inputPath, String message) {
                System.out.println("decompilationFailed");
            }
            public void fileDecompiled(List<String> inputPath, String outputPath) {
            }
            public boolean isCancelled() {
                return false;
            }
        });
        if (!res.getFailures().isEmpty()) {
            StringBuilder sb = new StringBuilder();
            sb.append("Failed decompilation of " + res.getFailures().size() + " classes: ");
            Iterator failureIterator = res.getFailures().iterator();
            while (failureIterator.hasNext()) {
                DecompilationFailure dex = (DecompilationFailure)failureIterator.next();
                sb.append(System.lineSeparator() + "    ").append(dex.getMessage());
            }
            System.out.println(sb.toString());
        }
        System.out.println("Compilation results: " + res.getDecompiledFiles().size() + " succeeded, " + res.getFailures().size() + " failed.");
        dec.close();
        Long end = System.currentTimeMillis();
        return end - start;
    }
}

Procyon 在反编译时会实时输出反编译文件数量的进度情况,最后还会统计反编译成功和失败的 Class 文件数量。

....
五月 15, 2021 10:58:28 下午 org.jboss.windup.decompiler.procyon.ProcyonDecompiler$3 call
信息: Decompiling 650 / 783
五月 15, 2021 10:58:30 下午 org.jboss.windup.decompiler.procyon.ProcyonDecompiler$3 call
信息: Decompiling 700 / 783
五月 15, 2021 10:58:37 下午 org.jboss.windup.decompiler.procyon.ProcyonDecompiler$3 call
信息: Decompiling 750 / 783
decompilationProcessComplete
Compilation results: 783 succeeded, 0 failed.
decompiler time: 40599ms

Procyon GUI

对于 Procyon 反编译来说,在 GitHub 上也有基于此实现的开源 GUI 界面,感兴趣的可以下载尝试。

Github 地址:https://github.com/deathmarine/Luyten

CFR

GitHub 地址:https://github.com/leibnitz27/cfr

CFR 官方网站:http://www.benf.org/other/cfr/(可能需要FQ)

Maven 仓库:https://mvnrepository.com/artifact/org.benf/cfr

CFR(Class File Reader) 可以支持 Java 9、Java 12、Java 14 以及其他的最新版 Java 代码的反编译工作。而且 CFR 本身的代码是由 Java 6 编写,所以基本可以使用 CFR 在任何版本的 Java 程序中。值得一提的是,使用 CFR 甚至可以将使用其他语言编写的的 JVM 类文件反编译回 Java 文件。

CFR 命令行使用

使用 CFR 反编译时,你可以下载已经发布的 JAR 包,进行命令行反编译,也可以使用 Maven 引入的方式,在代码中使用。下面先说命令行运行的方式。

直接在 GitHub Tags 下载已发布的最新版 JAR. 可以直接运行查看帮助。

# 查看帮助
java -jar cfr-0.151.jar --help

如果只是反编译某个 class.

# 反编译 class 文件,结果输出到控制台
java -jar cfr-0.151.jar WindupClasspathTypeLoader.class
# 反编译 class 文件,结果输出到 out 文件夹
java -jar cfr-0.151.jar WindupClasspathTypeLoader.class --outputpath ./out

反编译某个 JAR.

# 反编译 jar 文件,结果输出到 output_jar 文件夹
➜  Desktop java -jar cfr-0.151.jar decompiler.jar --outputdir ./output_jar
Processing decompiler.jar (use silent to silence)
Processing com.strobel.assembler.metadata.ArrayTypeLoader
Processing com.strobel.assembler.metadata.ParameterDefinition
Processing com.strobel.assembler.metadata.MethodHandle
Processing com.strobel.assembler.metadata.signatures.FloatSignature
.....

反编译结果会按照 class 的包路径写入到指定文件夹中。微信图片_20220414170935.jpg

CFR 代码中使用

添加依赖这里不提。

<!-- https://mvnrepository.com/artifact/org.benf/cfr -->
<dependency>
    <groupId>org.benf</groupId>
    <artifactId>cfr</artifactId>
    <version>0.151</version>
</dependency>

实际上我在官方网站和 GitHub 上都没有看到具体的单元测试示例。不过没有关系,既然能在命令行运行,那么直接在 IDEA 中查看反编译后的 Main 方法入口,看下命令行是怎么执行的,就可以写出自己的单元测试了。

package com.wdbyte.decompiler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.benf.cfr.reader.api.CfrDriver;
import org.benf.cfr.reader.util.getopt.OptionsImpl;
/**
 * CFR Test
 *
 * @author https://github.com/niumoo
 * @date 2021/05/15
 */
public class CFRTest {
    public static void main(String[] args) throws IOException {
        Long time = cfr("decompiler.jar", "./cfr_output_jar");
        System.out.println(String.format("decompiler time: %dms", time));
        // decompiler time: 11655ms
    }
    public static Long cfr(String source, String targetPath) throws IOException {
        Long start = System.currentTimeMillis();
        // source jar
        List<String> files = new ArrayList<>();
        files.add(source);
        // target dir
        HashMap<String, String> outputMap = new HashMap<>();
        outputMap.put("outputdir", targetPath);
        OptionsImpl options = new OptionsImpl(outputMap);
        CfrDriver cfrDriver = new CfrDriver.Builder().withBuiltOptions(options).build();
        cfrDriver.analyse(files);
        Long end = System.currentTimeMillis();
        return (end - start);
    }
}


相关文章
|
1月前
|
算法 Java
java面向对象和面向过程分析
java面向对象和面向过程分析
36 0
|
1月前
|
存储 Java 编译器
java和c++的主要区别、各自的优缺点分析、java跨平台的原理的深度解析
java和c++的主要区别、各自的优缺点分析、java跨平台的原理的深度解析
75 0
|
9天前
|
Java 调度
Java中常见锁的分类及概念分析
Java中常见锁的分类及概念分析
15 0
|
9天前
|
Java
Java中ReentrantLock中tryLock()方法加锁分析
Java中ReentrantLock中tryLock()方法加锁分析
11 0
|
29天前
|
Java
java中日期处理的一些工具方法
java中日期处理的一些工具方法
17 1
|
25天前
|
人工智能 监控 算法
java智慧城管源码 AI视频智能分析 可直接上项目
Java智慧城管源码实现AI视频智能分析,适用于直接部署项目。系统运用互联网、大数据、云计算和AI提升城市管理水平,采用“一级监督、二级指挥、四级联动”模式。功能涵盖AI智能检测(如占道广告、垃圾处理等)、执法办案、视频分析、统计分析及队伍管理等多个模块,利用深度学习优化城市管理自动化和智能化,提供决策支持。
200 4
java智慧城管源码 AI视频智能分析 可直接上项目
|
9天前
|
Java
Java中关于ConditionObject的signal()方法的分析
Java中关于ConditionObject的signal()方法的分析
21 4
|
9天前
|
Java
Java中关于ConditionObject的分析
Java中关于ConditionObject的分析
17 3
|
12天前
|
设计模式 缓存 安全
分析设计模式对Java应用性能的影响,并提供优化策略
【4月更文挑战第7天】本文分析了7种常见设计模式对Java应用性能的影响及优化策略:单例模式可采用双重检查锁定、枚举实现或对象池优化;工厂方法和抽象工厂模式可通过对象池和缓存减少对象创建开销;建造者模式应减少构建步骤,简化复杂对象;原型模式优化克隆方法或使用序列化提高复制效率;适配器模式尽量减少使用,或合并多个适配器;观察者模式限制观察者数量并使用异步通知。设计模式需根据应用场景谨慎选用,兼顾代码质量和性能。