From e664a406ddee0c53f816e911d5be18d4a330974b Mon Sep 17 00:00:00 2001 From: Jovan Gerodetti Date: Sun, 25 Sep 2016 16:26:46 +0200 Subject: [PATCH] wrapper for the native sha-256 algorithm --- modules/sha-256.js | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 modules/sha-256.js diff --git a/modules/sha-256.js b/modules/sha-256.js new file mode 100644 index 0000000..5200621 --- /dev/null +++ b/modules/sha-256.js @@ -0,0 +1,36 @@ + + +let binaryToHex = function(buffer) { + let result = ''; + + // choose chunk size + if (buffer.length * 8 % 32 === 0) { + buffer = new Uint32Array(buffer); + } else if (buffer.length * 8 % 16 === 0) { + buffer = new Uint16Array(buffer); + } else { + buffer = new Uint8Array(buffer); + } + + buffer.forEach(chunk => { + chunk = chunk.toString(16); + + while (chunk.length < (buffer.BYTES_PER_ELEMENT * 2)) { + chunk = '0' + chunk; + } + + result += chunk; + }); + + return result; +} + +export const sha256Native = function(data) { + if (typeof data === 'string') { + data = (new TextEncoder('utf-8')).encode(data); + } + + return window.crypto.subtle.digest('SHA-256', data).then(hashBuffer => { + return binaryToHex(hashBuffer); + }); +}