我有以下场景:我需要对我的字符串进行编码,然后我必须对我的值进行解码。
编码后的字符串应与字符串本身具有相同的长度。我的输入字符串只有 = Alpha 和 Number 值。
例如:
String="Test12345" (lenght : 9)
Encode = (encode should lenght 9)
Decode = Test12345
我尝试了不同的 CharcodeAt 、 FromCharCode 函数,但我得到了更长的编码字符串。我找不到解决方案。
查看我编写代码的输出值:
1. Your Input String:
Test12345
2. Encoded String:
4R4A3W3V5Q5P5O5N5M
3. Result : Decoded/Actual Input String:
Test12345
代码:
String.prototype.toEncodedString = function()
{
var ostr=this.toString().replace(/\s+/g,'');
var x,nstr='',len=ostr.length;
for(x=0;x<len;++x)
{
nstr+=(255-ostr.charCodeAt(x)).toString(36).toUpperCase();
};
return nstr;
};
String.prototype.fromEncodedString = function() {
var ostr=this.toString();
var x,nstr='',len=ostr.length;
for(x=0;x<len;x+=2)
{
nstr+=String.fromCharCode(255-parseInt(ostr.substr(x,2),36));
};
return nstr;
};
有人可以帮我解决这个问题吗?
最佳答案
最基本的是,您可以对每个字符进行异或 - 这是一个可逆操作,因此再次调用函数将解码字符串。例如
String.prototype.encodeDecode = function()
{
var nstr=''
for (var i=0; i < this.length; i++) {
nstr += String.fromCharCode(this.charCodeAt(i) ^ 1);
}
return nstr;
};
编码:
"Test12345".encodeDecode() // will produce "Udru03254"
解码:
"Udru03254".encodeDecode() // will produce "Test12345"
您可以修改此函数(例如,如果您使用 ^ i
而不是 ^ 1
- 输入中的相同字符将在输出中编码为不同的字符)
但正如 Barmar 指出的那样 - 这是非常基本的,如果安全性确实至关重要 - 您应该研究真正的加密方法。
关于javascript - 如何使用 Javascript 进行编码和解码(给定的字符串长度应与编码字符串长度匹配),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22534937/