javascript实现的字符串与十六进制表示字符串相互转换方法
本文实例讲述了javascript实现的字符串与十六进制表示字符串相互转换方法。分享给大家供大家参考。具体如下:
之所以写这个,是因为发现SQL注入和XSS中经常利用十六进制表示的字符串,比如
SELECTCONCAT(0x68656c6c6f);
得到的是hello
<!DOCTYPEhtml> <html> <head> <title>Hex-CharBi-Converter</title> </head> <body> <divclass="mainContainer"> <labelfor="from"id="fromLabel">String</label> <inputtype="text"name="from"id="from"/> <inputtype="button"name="exchange"id="exchange"value="<=>"/> <labelfor="to"id="toLabel">Hex</label> <inputtype="text"name="to"id="to"/> <inputtype="button"name="convert"id="convert"value="Convert"/> </div> <scripttype="text/javascript"src="js/jquery-1.9.1.min.js"></script> <scripttype="text/javascript"> varcurMode=0;//curMode:0representsStringtoHex,1fromHextoString varfromToLabelArray=["Hex","String"]; $(function(){ $("#convert").click(function(){ varfromVal=$("#from").val(); vartoVal= curMode===0 ? strToHexCharCode(fromVal) : hexCharCodeToStr(fromVal); $("#to").val(toVal); }); $("#exchange").click(function(){ $("#fromLabel").text(fromToLabelArray[curMode]); $("#toLabel").text(fromToLabelArray[1-curMode]); curMode=1-curMode; }); }); functionstrToHexCharCode(str){ if(str==="") return""; varhexCharCode=[]; hexCharCode.push("0x"); for(vari=0;i<str.length;i++){ hexCharCode.push((str.charCodeAt(i)).toString(16)); } returnhexCharCode.join(""); } functionhexCharCodeToStr(hexCharCodeStr){ vartrimedStr=hexCharCodeStr.trim(); varrawStr= trimedStr.substr(0,2).toLowerCase()==="0x" ? trimedStr.substr(2) : trimedStr; varlen=rawStr.length; if(len%2!==0){ alert("IllegalFormatASCIICode!"); return""; } varcurCharCode; varresultStr=[]; for(vari=0;i<len;i=i+2){ curCharCode=parseInt(rawStr.substr(i,2),16);//ASCIICodeValue resultStr.push(String.fromCharCode(curCharCode)); } returnresultStr.join(""); } </script> </body> </html>
希望本文所述对大家的javascript程序设计有所帮助。