Skip to content

Instantly share code, notes, and snippets.

@dotproto
Created June 9, 2017 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotproto/e59e05318f1356da963a3f8b3effed28 to your computer and use it in GitHub Desktop.
Save dotproto/e59e05318f1356da963a3f8b3effed28 to your computer and use it in GitHub Desktop.
Hash utils
// Generate a random hex string of the specified length
var randomHashReadable = function(length = 32) {
const hashLength = Math.ceil(length / 2);
const buffer = crypto.getRandomValues(new Uint8Array(hashLength));
const hex = [].slice.call(buffer).map(val => val.toString(16).padStart(2, '0'));
return hex.join('').substring(0, length);
};
var randomHash = (length = 32) => {
return hex = [].slice.call(crypto.getRandomValues(new Uint8Array(Math.ceil(length / 2)))).map(val => val.toString(16).padStart(2, '0')).join('').substring(0, length);
};
randomHash(32).then(log);
// =========================================================
// SHA 256 hash a given strinhg
var sha256 = function(str) {
if (typeof str !== 'string') {
throw new TypeError('Parameter must be a string');
}
var bytes = new Uint8Array(str.length);
for (var i = 0; i < str.length; i++) {
bytes[i] = str.charCodeAt(i);
}
return crypto.subtle.digest('SHA-256', bytes)
.then(buffer => {
let dv = new DataView(buffer);
const arr = new Array(dv.byteLength);
for(let i = 0; i < dv.byteLength; i++) {
arr[i] = dv.getUint8(i).toString(16).padStart(2, '0');
}
return arr.join('')
});
}
sha256('hello world').then(log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment