SHA-256 for JavaScript

SHA-256 is a 32-bit cryptographically secure hash function. While the most known SHA-1 function is still considered to be secure it was already reported that collisions may be found. Therefore it is recommended to use the next generation functions of SHA-2 that have similar structure but produce longer digests and no weakness have been found yet. The FIPS PUB 180-2 specifies three SHA-2 functions, namely 32-bit SHA-256, 64-bit SHA-512 and it's shortened version SHA-384. There is also SHA-224 function which was later defined to be shortened version of SHA-256.

Here I present simple implementation of 32-bit secure hash algorithm SHA-256 in JavaScript. I have not implemented the others SHA-2 functions because none JavaScript implementations provide 64-bit integer type and therefore all workarounds would be terribly slow and impractical. SHA-224 can be easily done with very few changes in current code but this function wasn't specified in FIPS PUB 180-2 which I used as reference.

This implementation contains three useful functions. Single function sha256 takes binary string of data and returns 32B (256 bits) binary string of its hash. To get the usual hexadecimal representation of hash value binhex function may be used. Please note that JavaScript strings are not byte-oriented but consist of Unicode characters. Only lower eight bits of each character value is taken, so input should be probably encoded into binary string before processing. To simplify this task, I have added utf8enc function that encodes Unicode string to UTF-8 binary (note that most software have problems with handling characters above U+FFFF, this is not bug of this script but of environment in which it runs). You are free to use this code under the terms of GNU General Public License.



Source: sha256.js
Reference: FIPS PUB 180-2

GPL v3

©2008 mwgamera, GPLv3