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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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);
});

No comments:

Post a Comment