简体   繁体   English

如何在Javascript中执行以base64编码的代码

[英]How to execute a code encoded in base64 in Javascript

I have this code in an html page (JavaScript): 我在html页面(JavaScript)中有以下代码:

<script>
    var cox,d = 0;
    Console.Log(cox,d);
</script>

Now I encrypted [var cox,d = 0; Console.Log(cox,d);] 现在,我加密了[var cox,d = 0; Console.Log(cox,d);] [var cox,d = 0; Console.Log(cox,d);] manually with base64 encode and the result is this: IHZhciBjb3gsZCA9IDA7DQogQ29uc29sZS5Mb2coY294LGQpOw== [var cox,d = 0; Console.Log(cox,d);]手动使用base64编码,结果是这样的: IHZhciBjb3gsZCA9IDA7DQogQ29uc29sZS5Mb2coY294LGQpOw==

I want that this encoded string (the code) could be executed by another JavaScript function in the same page... example: 我希望此编码的字符串(代码)可以由同一页面中的另一个JavaScript函数执行...示例:

<script>
    var encoded = "IHZhciBjb3gsZCA9IDA7DQogQ29uc29sZS5Mb2coY294LGQpOw==";
    var decodedString = atob(encoded);
    /* Problem is here */
</script>

I want to execute the JavaScript code (encoded above) in /* Problem is here */ '. 我想在/* Problem is here */执行JavaScript代码(上面编码)。 /* Problem is here */ '。

How can I do? 我能怎么做?

You can use the eval function (it is not recommended) , but it solves your problem. 您可以使用eval函数(不建议使用) ,但是它可以解决您的问题。

 /* var cox,d = 0; console.log(cox,d); */ var encoded = "dmFyIGNveCxkID0gMDsgY29uc29sZS5sb2coY294LGQpOw=="; var decodedString = atob(encoded); eval(decodedString); 

Another way of doing it, is using the New Function constructor 另一种方法是使用New Function构造函数

 /* var cox,d = 0; console.log(cox,d); */ var encoded = "dmFyIGNveCxkID0gMDsgY29uc29sZS5sb2coY294LGQpOw=="; var decodedString = atob(encoded); var func = new Function(decodedString); func(); 

*When encodeding your code, Console and Log must be lowercase and not ucfirst. *对代码进行编码时,Console和Log必须小写,而不是ucfirst。

I am not a security expert, and I truely advice you to check the risks of evaluating and executing this kind of functions in your apps. 我不是安全专家,因此我真的建议您检查在您的应用中评估和执行这种功能的风险。

Here is an interesting answer about the difference between eval and new Function 这是有关evalnew Function之间的区别的有趣答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM