-
-
Notifications
You must be signed in to change notification settings - Fork 645
Tutorial for MessageDigest class
Kenji Urushima edited this page May 10, 2013
·
14 revisions
The KJUR.crypto.MessageDigest class is a very similar to Java JCE [java.security.MessageDigest] (http://docs.oracle.com/javase/7/docs/api/index.html?java/security/MessageDigest.html) class for cryptographic hash algorithm calculation. So it's easy to learn.
Here is a basic example for 'SHA1' hash calculation.
// initialize
var md = new KJUR.crypto.MessageDigest({"alg": "sha1", "prov": "cryptojs"});
// update data
md.updateString('aaa')
// SHA1 hash result of string aaa which will be 7e240de74fb1ed08fa08d38063f6a6a91462a815
var hashValueHex = md.digest()
You can also update a hexadecimal string as hash input.
var md = new KJUR.crypto.MessageDigest({"alg": "sha1", "prov": "cryptojs"});
md.updateHex('5f6de0');
var hashValueHex = md.digest();
The 'updateHex' and 'updateString' method can be called one or more times.
var md = new KJUR.crypto.MessageDigest({"alg": "sha1", "prov": "cryptojs"});
md.updateHex('9a3bcd345793173');
md.updateHex('5f6de0');
md.updateString('abcdefg');
md.updateHex('01341571fg56ab');
md.updateString('apple');
var hashValueHex = md.digest();
To update and digest in a one method you can use 'digestHex' or 'digestString' method.
var md = new KJUR.crypto.MessageDigest({"alg": "sha1", "prov": "cryptojs"});
var hashValueHex = md.digestHex('1afcdd');
var md = new KJUR.crypto.MessageDigest({"alg": "sha1", "prov": "cryptojs"});
var hashValueHex = md.digestString('orange');
Currently MessageDigest class supports 'sha1' and 'cryptojs' only. However other algorithms and providers will be supported near in the future.
To use MessageDigest class following codes will be required.
<script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/components/core-min.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/components/sha1.js"></script>
<script src="http://kjur.github.io/jsrsasign/crypto-1.0.js"></script>