Skip to content

Instantly share code, notes, and snippets.

@neftaly
Last active August 29, 2015 14:10
Show Gist options
  • Save neftaly/8c008c60048277f63ec2 to your computer and use it in GitHub Desktop.
Save neftaly/8c008c60048277f63ec2 to your computer and use it in GitHub Desktop.
Generate a secure 128-bit hexadecimal key
/*
Generates a secure random 128-bit hexadecimal key
e.g. "a1ddeb99-14fcd49b-9b5e8e7f-e901bca0"
*/
function generateRandomKey(seed) {
var key = "";
if (window.crypto) {
var key32 = new Uint32Array(4);
key32 = window.crypto.getRandomValues(key32);
// Can't array.reduce() on typed arrays, unfortunately.
/*
replace the for loop below with:
var keySegment = 0;
while (key += key32[keySegment].toString(16), keySegment++ < key32.length) key+= "-";
*/
for (keySegment = 0; keySegment < key32.length; keySegment++) {
key += (keySegment > 0) ? "-" : ""; // Add delimiter
key += key32[keySegment].toString(16); // Convert int to hex
}
}
// Proper RNG is unsupported, so make a key with provider's seed
else if (seed) {
//
// key = best-effort seeded PRNG key
//
}
// Proper RNG is unsupported, and provider hasn't given us a seed yet
else {
key = false;
}
return key;
}
/*
Try to load saved key, else generate a new one
*/
function securityKey(seed) {
var key = $.cookie("bthack_key");
// Key is unset or invalid; create a new one
if (key.length !== 8*4+3) {
key = generateRandomKey(seed);
$.cookie("bthack_key", key, { expires: 365 });
}
return key;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment