AST混淆与解混淆笔记:字符串常量加密

本文主要是作者记笔记为主,温故而知新,记录混淆和解混淆的代码,后期可能会更新文章细节
以以下代码为例:

function test(a, b){
	const c = "123";
	a = a + 1 // a
	a = a + 2
	a = a * 1234
	a = a.toString()
	a = a.substring(0, 3)
	b = a + "00"
	return b;
}
test(2)
console.log(test(1))

首先导入库

const fs = require('fs');
const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const types = require("@babel/types");
const generator = require("@babel/generator").default;

const jscode = fs.readFileSync("./test2.js", {
    encoding: "utf-8"
});
let ast = parser.parse(jscode);

将"123", "00"字符串转换为base加密后的字符串,在通过调用atob来解密,混淆代码如下:

// 混淆代码,将字符串常量加密
const obstrfun ={
    StringLiteral(path){
        if (types.isStringLiteral(path.node)) {
            console.log(path.node.value)
            let result = btoa(path.node.value);
            let strcall = types.callExpression(types.identifier("atob"), [types.StringLiteral(result)])
            path.replaceWith(strcall);
        }
        path.skip()
    }
}
traverse(ast, obstrfun)

混淆后的代码如下:

function test(a, b) {
  const c = atob("MTIz");
  a = a + 1; // a
  a = a + 2;
  a = a * 1234;
  a = a.toString();
  a = a.substring(0, 3);
  b = a + atob("MDA=");
  return b;
}
test(2);
console.log(test(1));

还原混淆的代码如下:

// 混淆代码,将字符串常量加密(解混淆)
const obstrfun = {
    CallExpression(path) {
        // console.log(path.node)
        if (types.isCallExpression(path.node) && types.isIdentifier(path.node.callee, {name: 'atob'})) {
            // console.log(path.node.arguments[0]);
            let str = path.node.arguments[0].value;
            let result = atob(str);
            // console.log(str,result)
            path.replaceWith(types.stringLiteral(result));
        }

    }
}
traverse(ast, obstrfun)

你可能感兴趣的:(AST解混淆笔记,笔记,javascript,ast解混淆)