JavaScript – Get SHA-1 Hash of a String
This post shows you how to get SHA-1
hash of a string using JavaScript. To do this, we need to use thirty party SHA-1 JS libraries such as js-sha1.
1. Install js-sha1 library
- Download the library manually:
You can download it on its github repository.
- Via bower:
bower install js-sha1
- Via node.js/npm:
npm install js-sha1
2. Include js-sha1 library in your application
<script src="path/to/sha1.js"></script>
or if you use node.js
sha1 = require('js-sha1');
or if you use AMD
require(['path/to/sha1.js'], function(sha1) {
// CODE GOES HERE
});
3. Use js-sha1 library
- Way 1:
var myMessage = 'Message to hash';
// hash the message
var hashed = sha1(myMessage);
console.log(hashed);
- Way 2:
var myMessage = 'Message to hash';
// hash the message
var hash = sha1.create();
hash.update(myMessage);
var hashed = hash.hex();
console.log(hashed);
Output:
ad8b1ef19620cf94a1c0c9d6c87e7d1b2bca2584