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