[英]Word Array to String
how to do this in Javascript or Jquery? 如何在Javascript或Jquery中执行此操作?
Please suggest in 2 steps: 请通过两个步骤建议:
1.- Word Array to Single Byte Array. 1.-字阵列到单字节数组。
2.- Byte Array to String. 2.-字节数组到字符串。
Maybe this can help: 也许这可以帮助:
function hex2a(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
What you are trying to achieve is already implemented in CryptoJS. 您尝试实现的目标已在CryptoJS中实现。 From the documentation :
从文档 :
You can convert a WordArray object to other formats by explicitly calling the toString method and passing an encoder.
您可以通过显式调用toString方法并传递编码器将WordArray对象转换为其他格式。
var hash = CryptoJS.SHA256("Message");
alert(hash.toString(CryptoJS.enc.Base64));
alert(hash.toString(CryptoJS.enc.Hex));
Honestly I have no idea why you want to implement that yourself... But if you absolutely need to do it "manually" in the 2 steps you mentioned, you could try something like this: 老实说,我不知道你为什么要自己实现......但如果你绝对需要在你提到的两个步骤中“手动”完成它,你可以尝试这样的事情:
function wordToByteArray(wordArray) {
var byteArray = [], word, i, j;
for (i = 0; i < wordArray.length; ++i) {
word = wordArray[i];
for (j = 3; j >= 0; --j) {
byteArray.push((word >> 8 * j) & 0xFF);
}
}
return byteArray;
}
function byteArrayToString(byteArray) {
var str = "", i;
for (i = 0; i < byteArray.length; ++i) {
str += escape(String.fromCharCode(byteArray[i]));
}
return str;
}
var hash = CryptoJS.SHA256("Message");
var byteArray = wordToByteArray(hash.words);
alert(byteArrayToString(byteArray));
The wordToByteArray
function should work perfectly, but be aware that byteArrayToString
will produce weird results in almost any case. wordToByteArray
函数应该可以正常工作,但要注意byteArrayToString
几乎在任何情况下都会产生奇怪的结果。 I don't know much about encodings, but ASCII only uses 7 bits so you won't get ASCII chars when trying to encode an entire byte. 我对编码知之甚少,但ASCII只使用7位,因此在尝试编码整个字节时不会得到ASCII字符。 So I added the
escape
function to at least be able to display all those strange chars you might get. 所以我添加了
escape
函数,至少能够显示你可能得到的所有奇怪的字符。 ;) ;)
I'd recommend you use the functions CryptoJS has already implemented or just use the byte array (without converting it to string) for your analysis. 我建议您使用CryptoJS已经实现的函数,或者只使用字节数组(不将其转换为字符串)进行分析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.