Java中使用FernFlower反编译Class文件

Java中使用FernFlower反编译Class文件

引入maven依赖

<dependency>
    <groupId>org.jboss.windup.decompiler</groupId>
    <artifactId>decompiler-fernflower</artifactId>
    <version>5.1.0.Final</version>
</dependency>

类实现

import cn.hutool.core.io.file.FileReader;
import org.jboss.windup.decompiler.api.*;
import org.jboss.windup.decompiler.fernflower.FernFlowerResultSaver;
import org.jboss.windup.decompiler.fernflower.FernflowerDecompiler;
import org.jboss.windup.decompiler.fernflower.FernflowerJDKLogger;
import org.jboss.windup.util.exception.WindupStopException;
import org.jetbrains.java.decompiler.main.Fernflower;
import org.jetbrains.java.decompiler.main.extern.IBytecodeProvider;
import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences;
import org.jetbrains.java.decompiler.util.InterpreterUtil;
import vip.okfly.cactus.common.util.CommonUtil;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

public class Decompiler extends FernflowerDecompiler {

    public String decompile(String projectName, byte[] bytes) {
        try {

            // 1. 定义反编译后代码存储位置
            String sourceFolder = "/tmp/.cactus/decompile/" + projectName + "/";
            File sourceFileFolder = new File(sourceFolder);
            if (!sourceFileFolder.exists()) {
                sourceFileFolder.mkdirs();
            }

            // 2. 将字节数组保存为class文件
            String uuid = UUID.randomUUID().toString();
            File classFile = new File("/tmp/.cactus/decompile/" + projectName + "/" + uuid + ".class");
            CommonUtil.saveBytes(bytes, classFile);

            // 3. 调用ConsoleDecompiler
            return decompile(projectName, classFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * 参数是class文件
     * @param classFile
     */
    public String decompile(String projectName, File classFile) {

        try {

            // 1. 定义反编译后代码存储位置
            String sourceFolder = "/tmp/.cactus/decompile/" + projectName + "/";
            File sourceFileFolder = new File(sourceFolder);
            if (!sourceFileFolder.exists()) {
                sourceFileFolder.mkdirs();
            }

            // 3. 调用ConsoleDecompiler
            DecompilationResult result = decompileClassFile(Paths.get(classFile.getAbsolutePath()), Paths.get(sourceFolder));
            if (result.getFailures().size() > 0) {
                return "";
            }

            // 4. 获取编译后的文件
            Map<String, String> decompiles = result.getDecompiledFiles();
            File sourceCodeFile = new File(decompiles.values().iterator().next());

            FileReader fileReader = new FileReader(sourceCodeFile);
            String code = fileReader.readString();

            // 清除缓存文件
            classFile.delete();
            sourceCodeFile.delete();

            return code;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    private Map<String, Object> getOptions() {
        Map<String, Object> options = new HashMap<>();
        options.put(IFernflowerPreferences.REMOVE_BRIDGE, "0");
        options.put(IFernflowerPreferences.LAMBDA_TO_ANONYMOUS_CLASS, "1");
        options.put(IFernflowerPreferences.BYTECODE_SOURCE_MAPPING, "1");
        options.put(IFernflowerPreferences.DUMP_ORIGINAL_LINES, "1");
        return options;
    }

    public DecompilationResult decompileClassFile(Path classFilePath, Path outputDir) throws DecompilationException {
        final DecompilationResult result = new DecompilationResult();
        DecompilationListener listener = new DecompilationListener() {
            private boolean cancelled;

            @Override
            public void fileDecompiled(List<String> inputPath, String outputPath) {
                try {
                    result.addDecompiled(inputPath, outputPath);
                }
                catch (WindupStopException stop) {
                    this.cancelled = true;
                    throw new WindupStopException(stop);
                }
            }

            @Override
            public void decompilationFailed(List<String> inputPath, String message) {
                result.addFailure(new DecompilationFailure(message, inputPath, null));
            }

            @Override
            public void decompilationProcessComplete(){
            }

            @Override
            public boolean isCancelled() {
                return this.cancelled;
            }
        };

        FernFlowerResultSaver resultSaver = getResultSaver(Collections.singletonList(classFilePath.toString()), outputDir.toFile(), listener);
        Fernflower fernflower = new Fernflower(getByteCodeProvider(), resultSaver, getOptions(), new FernflowerJDKLogger());
        fernflower.getStructContext().addSpace(classFilePath.toFile(), true);
        fernflower.decompileContext();

        if (!resultSaver.isFileSaved()) {
            listener.decompilationFailed(Collections.singletonList(classFilePath.toString()), "File was not decompiled!");
        }

        return result;
    }

    private IBytecodeProvider getByteCodeProvider() {
        return new IBytecodeProvider() {
            @Override
            public byte[] getBytecode(String externalPath, String internalPath) throws IOException {
                return InterpreterUtil.getBytes(new File(externalPath));
            }
        };
    }

    private FernFlowerResultSaver getResultSaver(final List<String> requests, File directory, final DecompilationListener listener) {
        return new FernFlowerResultSaver(requests, directory, listener);
    }

}

测试

测试用的Java类

package vip.okfly.cactus.ui.controller;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.okfly.cactus.ui.service.ToutService;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

//    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    private String okFly = "okFly";

    private static final String cici = "cicia";

    private final String CSED = "CSED";

    public int intFiled0 = 10;
    public byte byteFiled0 = 11;
    public short shortField0 = 13;
    public char charField0 = 'A';
    public boolean booleanField0 = true;
    public float floatField0 = 1.0f;
    public double doubleField0 = 2.0d;
    private long longField0 = 3l;

    @Autowired
    private ToutService toutService;

    @RequestMapping("/p")
    public String test(String p1, String p2) {

        int intFiled1 = 10;
        byte byteFiled1 = 11;
        short shortField1 = 13;
        char charField1 = 'A';
        boolean booleanField1 = true;
        float floatField1 = 1.0f;
        double doubleField1 = 2.0d;
        long longField1 = 3l;

        System.out.println(p1 + p2);
        if (p1.equals(p2)) {
            return p1 + p2;
        }

        Map<String, Object> objMap = new HashMap<>();
        objMap.put(p1, cici);
        objMap.put(p2, CSED);

//        log.info("p1p2: {}", p1 + p2);

        return "ok";
    }

}

反编译后的结果

在这里插入图片描述

说明

FernFlower 的代码反编译能力还是很不错的,我在配置中显示了行号,在代码的后面使用 // 行号 表示,这样就可以知道反编译出来的代码对应于源代码中的第几行了。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值