javascript实现的字符串与⼗六进制表⽰字符串相互转换
⽅法
本⽂实例讲述了javascript实现的字符串与⼗六进制表⽰字符串相互转换⽅法。分享给⼤家供⼤家参考。具体如下:
之所以写这个,是因为发现SQL注⼊和XSS中经常利⽤⼗六进制表⽰的字符串,⽐如
SELECT CONCAT(0x68656c6c6f);
得到的是hello
<!DOCTYPE html>
<html>
<head>
<title>Hex-Char Bi-Converter</title>
</head>
<body>
<div class="mainContainer">
<label for="from" id="fromLabel">String</label>
<input type="text" name="from" id="from" />
<input type="button" name="exchange" id="exchange" value="<=>" />
<label for="to" id="toLabel">Hex</label>
<input type="text" name="to" id="to" />
<input type="button" name="convert" id="convert" value="Convert" />
</div>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
var curMode = 0; // curMode: 0 represents String to Hex, 1 from Hex to String
var fromToLabelArray = ["Hex", "String"];
$(function() {
$("#convert").click(function() {
var fromVal = $("#from").val();
var toVal =
curMode === 0
strToHexCharCode(fromVal)
:
hexCharCodeToStr(fromVal);
$("#to").val(toVal);
});
$("#exchange").click(function() {
$("#fromLabel").text(fromToLabelArray[curMode]);
$("#toLabel").text(fromToLabelArray[1-curMode]);
curMode = 1 - curMode;
});
});
function strToHexCharCode(str) {
if(str === "")
return "";
var hexCharCode = [];
hexCharCode.push("0x");
for(var i = 0; i < str.length; i++) {
hexCharCode.push((str.charCodeAt(i)).toString(16));
}
return hexCharCode.join("");
}
function hexCharCodeToStr(hexCharCodeStr) {
var trimedStr = im();
var rawStr =
trimedStr.substr(0,2).toLowerCase() === "0x"
trimedStr.substr(2)
:
trimedStr;
var len = rawStr.length;
if(len % 2 !== 0) {
alert("Illegal Format ASCII Code!");
return "";
}
var curCharCode;
var resultStr = [];
for(var i = 0; i < len;i = i + 2) {
curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
resultStr.push(String.fromCharCode(curCharCode));
}
16进制字符串转16进制数组return resultStr.join("");
}
</script>
</body>
</html>
希望本⽂所述对⼤家的javascript程序设计有所帮助。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论