Simple (non-secure) hash function for JavaScript?
There are many realizations of hash functions written in JS. For example:
- SHA-1: http://www.webtoolkit.info/javascript-sha1.html
- SHA-256: http://www.webtoolkit.info/javascript-sha256.html
- MD5: http://www.webtoolkit.info/javascript-md5.html
If you don't need security, you can also use base64 which is not hash-function, has not fixed output and could be simply decoded by user, but looks more lightweight and could be used for hide values: http://www.webtoolkit.info/javascript-base64.html
I didn't verify this myself, but you can look at this JavaScript implementation of Java's String.hashCode() method. Seems reasonably short.
With this prototype you can simply call
.hashCode()
on any string, e.g."some string".hashCode()
, and receive a numerical hash code (more specifically, a Java equivalent) such as 1395333309.
String.prototype.hashCode = function() {
var hash = 0;
for (var i = 0; i < this.length; i++) {
var char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
2022 EDIT:
It has been long accepted that modifying built-in prototypes is bad practice, so instead you should use a plain function:
/**
* Returns a hash code from a string
* @param {String} str The string to hash.
* @return {Number} A 32bit integer
* @see http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
*/
function hashCode(str) {
let hash = 0;
for (let i = 0, len = str.length; i < len; i++) {
let chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}