Skip to content

Commit

Permalink
wrapper for the native sha-256 algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
TitanNano committed Sep 25, 2016
1 parent 7bae8eb commit e664a40
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions modules/sha-256.js
Original file line number Diff line number Diff line change
@@ -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);
});
}

0 comments on commit e664a40

Please sign in to comment.