-1

我开始了解如何以及何时进行编码以减轻 XSS 和正确显示字符。

然而,我有一些客户端脚本(JavaScript)正在将一些 html 写入页面,特别是写入查询字符串。

为此,我使用了 javascript 的“encodeURIComponent”函数来帮助处理存储在外部 json 文件中的用户输入。

我注意到,无论我如何尝试对这些值进行编码,当尖括号位于任何值中时,它实际上每次都会锁定页面,但是当 json 值中没有尖括号时可以完美地工作。

我首先尝试了 html 编码,然后使用“encodeURIComponent”并反过来尝试。由于 javascript 没有天生的 html 编码器,我自己编写了一个简单的编码器。是这里:

function htmlEncode (input)
{

    while(input.indexOf("&") > -1)
    {
        input = input.replace("&", "&")
    }
    while(input.indexOf("<") > -1)
    {
        input = input.replace("<", "&lt;")
    }
    while(input.indexOf(">") > - 1)
    {
        input = input.replace(">", "&gt;")
    }
    while(input.indexOf("\"") > -1)
    {
        input = input.replace("\"", "&#x22;")
    }
    while(input.indexOf("'") > -1)
    {
        input = input.replace("'", "&#x27;")
    }
    while(input.indexOf("/") > -1)
    {
        input = input.replace("/", "&#x2F;")
    }

    return input
}

这是将值写入页面的代码的 javascript 片段(没有 html 编码器):

stringCompiler = "/Event htms/Event.cshtml?title=" + encodeURIComponent(jsonObj.events[i].title) +
                        "&explanation=" + encodeURIComponent(jsonObj.events[i].explanation) + "&dateString=" +
                        encodeURIComponent(jsonObj.events[i].dateMonth) + "-" + encodeURIComponent(jsonObj.events[i].dateNumber) + "-" + encodeURIComponent(jsonObj.events[i].dateYear);

不幸的是,我无法提供更多信息,因为当它锁定时,它会很难锁定,并且无法运行任何诊断工具(甚至无法右键单击或滚动)。

我认为编码两次是愚蠢的,但是当尖括号单独使用“encodeURIComponent”锁定浏览器时,我想我也会尝试 html 编码,但它仍然会锁定任何一种方式。

有什么我可以做的,还是应该在保存到 json 文件时防止尖括号?

------------------------这就是我在下面的函数中看到的-----

你的功能

4

1 回答 1

3

你可以做得这更好。我给你带来了我的好朋友,字母“g”:

function htmlEncode (input) {
  return input.replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\//g, '&#x2F;')
    .replace(/'/g, '&#x27;')
    .replace(/"/g, '&#x22;');
}

由于“&”,您的代码有问题。你的代码说:

  1. 这个字符串中有和号吗?
  2. 如果是,则将第一个替换为&amp;
  3. 转到步骤 1。

看到问题了吗?您将始终在字符串中使用&符号。通过.replace()在正则表达式上使用“全局”限定符,您可以在一次调用中替换所有这些。

还有另一种方法可以做到这一点,一种可能更快的方法,只涉及一次调用.replace()和一个函数参数,但我认为它不必要地复杂。

encodeURIComponent()不会在任何输入“挂起”,因为您可以在键入时看到自己

encodeURIComponent("<>&");

进入浏览器的控制台。

于 2013-03-05T20:30:18.117 回答