Javascript 使用编码防止Xss,但用户可读性很差
为了保护xss攻击,我尝试使用下面的函数对我想要显示给用户的每条消息进行编码Javascript 使用编码防止Xss,但用户可读性很差,javascript,xss,decode,encode,Javascript,Xss,Decode,Encode,为了保护xss攻击,我尝试使用下面的函数对我想要显示给用户的每条消息进行编码 function encodeRFC5987ValueChars(str) { return encodeURIComponent(str). // Note that although RFC3986 reserves "!", RFC5987 does not, // so we do not need to escape it replace(/['()]
function encodeRFC5987ValueChars(str)
{
return encodeURIComponent(str).
// Note that although RFC3986 reserves "!", RFC5987 does not,
// so we do not need to escape it
replace(/['()]/g, escape). // i.e., %27 %28 %29
replace(/\*/g, '%2A').
// The following are not required for percent-encoding per RFC5987,
// so we can allow for a little better readability over the wire: |`^
replace(/%(?:7C|60|5E)/g, unescape);
}
示例输入消息如下所示
Start 20 TV's test; star ;; '' -- testagain., comma. </>
我试着显示如下
Start%2020%20TV%27s%20test%3B%20star%20%3B%3B%20%27%27%20--%20testagain.%2C%20comma.%20%3C%2F%3E
document.getElementById("labelResult").innerHTML = "Start%2020%20TV%27s%20test%3B%20star%20%3B%3B%20%27%27%20--%20testagain.%2C%20comma.%20%3C%2F%3E";
一切正常,但用户可读性非常差。我需要解码吗?如果我解码,那么我怕会导致xss攻击吗
有什么建议吗 您正在将数据插入HTML,而不是URL 为了防御XSS,您需要为HTML正确编码XSS
encodeURIComponent
不应该在这附近
var textNode = document.createTextNode("Start 20 TV's test; star ;; '' -- testagain., comma. </>");
document.getElementById("labelResult").innerHTML = ""; // Erase existing content
document.getElementById("labelResult").appendChild(textNode);
var textNode=document.createTextNode(“开始20台电视的测试;星形;;”--testagain,逗号”);
document.getElementById(“labelResult”).innerHTML=“”;//删除现有内容
document.getElementById(“labelResult”).appendChild(textNode);
无论您使用什么方法进行
start20tv的测试,都可能有XSS的向量;星星;;“”--逗号
作为用户输入并将其放入JavaScript…但您还没有向我们展示如何做到这一点。我不会使用encodeURIComponent
来转义字符串,它将替换的内容太多了。看一下这个问题/答案:假设用户输入了必须保存在我的数据库中的消息。在保存到DB之前,我对其进行了编码并将其保存到DB中。当用户想要查看数据时,我必须检索数据并显示给用户。谢谢。在将其放入数据库之前不要对其进行编码(为了防止SQL注入,请使用准备好的语句和绑定变量)。在将其放入页面之前如何对其进行编码取决于将其从数据库中取出并放入页面所使用的方法。当页面加载时,是否将其放入HTML属性中?在带有页面加载的脚本元素中生成原始JavaScript?稍后使用XMLHttpRequest获取它并将其作为纯文本返回?三种不同的技术可以解决问题,三种不同的技术可以抵御SQL注入。