简体   繁体   中英

How to execute a code encoded in base64 in Javascript

I have this code in an html page (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);] manually with base64 encode and the result is this: IHZhciBjb3gsZCA9IDA7DQogQ29uc29sZS5Mb2coY294LGQpOw==

I want that this encoded string (the code) could be executed by another JavaScript function in the same page... example:

<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 */ '.

How can I do?

You can use the eval function (it is not recommended) , but it solves your problem.

 /* 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

 /* 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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