Menu

Thursday, June 30, 2016

Generating hash using native Crypto API (Example)

You can find more information about the crypto api here:  https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto

function arrayBufferToStringAsync( /*ArrayBuffer*/ buffer) {
    var reader = new FileReader();
    return readAsync(reader, 'Text', new Blob([buffer])).then(function() {
        return new Promise(function(resolve, reject) {
            resolve(reader.result);
        });
    });
};

function arrayBufferToHexAsync( /*ArrayBuffer*/ buffer) {
    return new Promise(function(success, error) {
        arrayBufferToStringAsync(buffer).then(function(string) {
            var hex = '';
            for (var i = 0; i < string.length; i++) {
                var char = ('000' + string.charCodeAt(i).toString(16)).slice(-4);
                hex += char;
            }

            success(hex);
        }).catch(error);
    });
};

function readAsync( /* FileReader */ reader, as, data, encoding) {
    return new Promise(function(resolve, reject) {
        reader.onloadend = resolve;
        reader.onerror = reject;
        reader['readAs' + as](data, encoding);
    });
};

var blob = new Blob(['Hello World']);
var reader = new FileReader();

readAsync(reader, 'ArrayBuffer', blob).then(function() {
    var result = reader.result;
    return crypto.subtle.digest("SHA-1", result);
}).then(function(hash) {
    return arrayBufferToHexAsync(hash);
}).then(function(hexHash) {
    console.log(hexHash);
});