In this tutorial I will show you code example of how to produce hash of data using Web Cryptography API.
Converting String to Array Buffer and Array Buffer to Hexadecimal String
If you need to produce hash value of text or binary data you first need to convert it to an array buffer type so that Web Cryptography API can hash it.
Here is an function to convert string/text to an array buffer type
{
var bytes = new Uint8Array(str.length);
for (var iii = 0; iii < str.length; iii++)
{
bytes[iii] = str.charCodeAt(iii);
}
return bytes;
}
After conversion Web Cryptography API returns hash value as hexadecimal in an array buffer. So we need to convert the array buffer to an hexadecimal string.
{
var data_view = new DataView(buffer)
var iii, len, hex = '', c;
for(iii = 0, len = data_view.byteLength; iii < len; iii += 1)
{
c = data_view.getUint8(iii).toString(16);
if(c.length < 2)
{
c = '0' + c;
}
hex += c;
}
return hex;
}
Generating Hash Value of a String
Here is the code to generate hash value of a string
var crypto = window.crypto || window.msCrypto;
if(crypto.subtle)
{
alert("Cryptography API Supported");
var promise = crypto.subtle.digest({name: "SHA-256"}, convertStringToArrayBufferView(data));
promise.then(function(result){
var hash_value = convertArrayBufferToHexaDecimal(result);
});
}
else
{
alert("Cryptography API not Supported");
}
Here we are using SHA-256 hash function. There are many other hashing functions supported such as SHA-1, SHA-512 etc.