Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

javascript - Word Array to String

how to do this in Javascript or Jquery?

Please suggest in 2 steps:

1.- Word Array to Single Byte Array.

2.- Byte Array to String.

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you are trying to achieve is already implemented in CryptoJS. From the documentation:

You can convert a WordArray object to other formats by explicitly calling the toString method and passing an encoder.

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. 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. So I added the escape function to at least be able to display all those strange chars you might get. ;)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...