3

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);] 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?

Rafik Tighilt
  • 2,071
  • 1
  • 15
  • 27
Programmer
  • 103
  • 1
  • 9

1 Answers1

6

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

Rafik Tighilt
  • 2,071
  • 1
  • 15
  • 27