Simple (non-secure) hash function for JavaScript? [duplicate]
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; if (this.length == 0) { return hash; } 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;}
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
Check out these implementations
- http://www.movable-type.co.uk/scripts/sha1.html (SHA-1 algorithm)
- http://pajhome.org.uk/crypt/md5/ (implementations for SHA-1, MD5, HMAC and others)