用于评估简单数学字符串的JavaScript,如5 * 1.2(eval / white-list?) [英] JavaScript to evaluate simple math string like 5*1.2 (eval/white-list?)

查看:73
本文介绍了用于评估简单数学字符串的JavaScript,如5 * 1.2(eval / white-list?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入onchange,它将 05008 等数字转换为 5,008.00

I have an input onchange that converts numbers like 05008 to 5,008.00.

我正在考虑对此进行扩展,以便进行简单的计算。例如, 45 * 5 将自动转换为 225.00

I am considering expanding on this, to allow simple calculations. For example, 45*5 would be converted automatically to 225.00.

我可以使用字符白名单()+ / * - 0123456789。,然后将结果传递给 eval ,我认为这些字符可以安全地防止任何危险的注射。假设我使用了适当的 try / catch ,因为可能会产生语法错误。

I could use a character white-list ()+/*-0123456789., and then pass the result to eval, I think that these characters are safe to prevent any dangerous injections. That is assuming I use an appropriate try/catch, because a syntax error could be created.


  • 这是一个好的白名单,然后将其传递给 eval

建议修改白名单

您是否建议使用其他方法(也许已经有一个功能可以做到这一点)

Do you recommend a different approach (maybe there is already a function that does this)

我宁愿保持它的轻量级。这就是我喜欢 eval / white-list方法的原因。非常少的代码。

I would prefer to keep it lightweight. That is why I like the eval/white-list approach. Very little code.

你推荐什么?

推荐答案

白名单看起来对我来说是安全的,但这不是一个简单的问题。在某些浏览器中,例如,像这样的eval-string:

That whitelist looks safe to me, but it's not such a simple question. In some browsers, for example, an eval-string like this:

/.(.)/(34)

相当于:

new RegExp('.(.)').exec('34')

因此返回数组 ['34','4'] 。这是安全吗?

and therefore returns the array ['34','4']. Is that "safe"?

因此虽然这种方法可能会安全地运作,但这可能是一个非常棘手的主张。如果你继续这个想法,我认为你应该使用很多更积极的方法来验证你的输入。你的原则应该是这是一个明确定义的字符串集合中的成员,已知为'安全',而不是这是一个不明确的字符串集合的成员,排除了所有已知的'不安全的字符串。此外,为了避免操作员偷看您未考虑的任何风险(例如 ++ + = 或者诸如此类的,我认为你应该在每个非数字非点字符前插入一个空格;并且为了避免括号触发函数调用的任何风险,我认为您应该通过反复替换(...)并使用空格加上评估<$的结果来自己处理它们c $ c> ... (确认结果是一个数字后)加上一个空格。

So while the approach can probably be made to work safely, it might be a very tricky proposition. If you do go forward with this idea, I think you should use a much more aggressive approach to validate your inputs. Your principle should be "this is a member of a well-defined set of strings that is known to be 'safe'" rather than "this is a member of an ill-defined set of strings that excludes all strings known to be 'unsafe'". Furthermore, to avoid any risk of operators peeking through that you hadn't considered (such as ++ or += or whatnot), I think you should insert a space in front of every non-digit-non-dot character; and to avoid any risk of parentheses triggering a function call, I think you should handle them yourself by repeatedly replacing (...) with a space plus the result of evaluating ... (after confirming that that result is a number) plus a space.

(顺便问一下,怎么回事 = 是否在您的白名单中?我无法弄清楚这对哪些有用!)

(By the way, how come = is in your whitelist? I just can't figure out what that's useful for!)

这篇关于用于评估简单数学字符串的JavaScript,如5 * 1.2(eval / white-list?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆