Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JeffCave/1e03099566920363beb4bc0454ef4400 to your computer and use it in GitHub Desktop.
Save JeffCave/1e03099566920363beb4bc0454ef4400 to your computer and use it in GitHub Desktop.
Convert a byte array to a word array and back in CryptoJS-compatible fashion
/**
* EXAMPLE
* var myhash = CryptoJS.HmacSHA1(mine[2], secret);
* myhash = byteArrayConversion(myhash);
*/
function wordArrayToByteArray(hash){
return hash.words
//map each word to an array of bytes
.map(function(v){
// create an array of 4 bytes (less if sigBytes says we have run out)
var bytes = [0,0,0,0].slice(0,Math.min(4,hash.sigBytes))
// grab that section of the 4 byte word
.map(function(d,i){ return (v >>> (8*i)) % 256; })
// flip that
.reverse()
;
// remove the bytes we've processed
// from the bytes we need to process
hash.sigBytes -= bytes.length;
return bytes;
})
// concatinate all the arrays of bytes
.reduce(function(a,d){ return a.concat(d);},[])
// convert the 'bytes' to 'characters'
.map(function(d){return String.fromCharCode(d);})
// create a single block of memory
.join('')
;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment