开发者

How Do I Sanitize JS eval Input?

开发者 https://www.devze.com 2023-03-06 07:40 出处:网络
a=\"79 * 2245 + (79 * 2 - 7)\"; b=\"\"; c=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"0\",\"+\",\"-\",\"/\",\"*\"];
a="79 * 2245 + (79 * 2 - 7)";
b="";
c=["1","2","3","4","5","6","7","8","9","0","+","-","/","*"];
for (i=1;i<a.length;i++){
  for (ii=1;i<c.length;i++){
    b=(a.substring(0,i))+(c[ii])+(a.substring(i+1,a.length));
    alert(eval(b.replace(" ","")));
  }
}

I need to find out how 开发者_JAVA百科to make it so that when I use eval, I know that the input will not stop the script, and if it would normally crash the script to just ignore it. I understand that eval is not a good function to use, but I want a quick and simple method by which I can solve this. The above code tries to output all of the answers with all of the possible replacements for any digit, sign or space in the above. i represents the distance through which it has gone in the string and ii represents the symbol that it is currently checking. a is the original problem and b is the modified problem.


Try catching the exception eval might throw, like this:

try{
  alert(eval(b.replace(" ","")));
} catch (e){
  //alert(e);
}


You can check for a few special cases and avoid some behaviors with regex or the like, but there is definitely no way to 'if it would normally crash just ignore it'

That is akin to the halting problem, as mellamokb refers to. And theres no way to know ipositively f a script runs to completion besides running it.

One should be very careful to vet any strings that go to eval, and keep user input out of them as much as possibl except for real simple and verifiable things like an integer value. If you can find a way around eval altogether than all the better.

For the calculation example you show its probably best to parse it properly into tokens and go from there rather than evaluate in string form.

PS - if you really want to check out these one-off's to the expression in a, it is a somewhat interesting use of eval eespite its faults. cam you explain why you are trimming the whitespace imediately before evaluation? i dont believe i can think of a situation where it effects the results. for (at least most) valid expressions it makes no difference, and while it might alter some of the invalid cases i cant think of a case where it does so meaningfully

0

精彩评论

暂无评论...
验证码 换一张
取 消