JavaScript Tricks: Undocumented Usage of Eval

本文介绍了JavaScript中Eval的一个鲜为人知的用法,通过将字符串转换为语法关键字,如`console.log`,实现代码加密和混淆。这种方法特别适用于隐藏关键代码,如处理JSON数据时保护键名。
摘要由CSDN通过智能技术生成

In JavaScript programming, Eval is typically used to execute JavaScript code, perform computations, and output results. However, there is an undocumented usage of Eval that few people are probably familiar with.

Here is an example:

var a = eval(['g', 'o', 'l', '.', 'e', 'l', 'o', 's', 'n', 'o', 'c'].reverse().join(""));
var b = ['m', 'o', 'c', '.', 'n', 'a', 'm', 'a', 'h', 's', 'j'].reverse().join("");
a(b);

Can you guess what the output of the function a(b) will be if you only look at the syntax of this JS code? The answer is surprisingly unexpected. Here it is:

The ability to produce such an output relies on an undocumented usage of Eval that allows converting strings into syntactic keywords. The simplified version of the Eval statement mentioned above would be:

eval("console.log");

Use reverse and join to hide the plaintext of console.log.

This method is used for encrypting JavaScript code and works quite well. When it comes to obfuscating and encrypting JS code, some signature words are difficult to hide, like console.log. Typically, console.log might be changed to console["log"] or console["\x6c\x6f\x67"], where the "log" characters can be transformed, but console as a syntax keyword cannot be changed, making it easy to be identified. However, this usage of eval can solve this issue and effectively hide many syntax keywords.

Or for example, for encrypting JSON data:

var abc ={a:'This is a', b:'This is b', c:'This is c'};
console.log(abc.a);
console.log(abc.b);
console.log(abc.c);

JSON data, due to its unique format, is notoriously difficult to obfuscate and encrypt with JavaScript, as it is often difficult to hide key names. However, using the method described in this article, you can modify the code to:

eval("var abc ={a:'This is a', b:'This is b', c:'This is c'};");
console.log(abc.a);
console.log(abc.b);
console.log(abc.c);

Encrypt the content inside the eval statement, and the encrypted code can become:

Note: This is done using JShaman JavaScript Obfuscator, the same applies below.

eval("\u0076\u0061\u0072\u0020\u0061\u0062\u0063\u0020\u003d\u007b\u0061\u003a\u0027\u0054\u0068\u0069\u0073\u0020\u0069\u0073\u0020\u0061\u0027\u002c\u0020\u0062\u003a\u0027\u0054\u0068\u0069\u0073\u0020\u0069\u0073\u0020\u0062\u0027\u002c\u0020\u0063\u003a\u0027\u0054\u0068\u0069\u0073\u0020\u0069\u0073\u0020\u0063\u0027\u007d\u003b");
console.log(abc.a);
console.log(abc.b);
console.log(abc.c);

output:

  • 24
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值