Skip to content

Instantly share code, notes, and snippets.

@mozfreddyb
Created April 15, 2016 09:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mozfreddyb/98843b728f61958f5c31e70d57d93fb8 to your computer and use it in GitHub Desktop.
Save mozfreddyb/98843b728f61958f5c31e70d57d93fb8 to your computer and use it in GitHub Desktop.
generate random strings, e.g., for passwords
/*
in one line for bookmarkletts:
javascript:!function(){"use strict";function r(){var r=new Uint8Array(n);window.crypto.getRandomValues(r);var r=Array.apply([],r);return r=r.filter(function(r){return r>32&&127>r}),String.fromCharCode.apply(String,r)}for(var n=50,t=20,a=r();a.length<t;)a+=r();prompt("",a)}();
*/
(function() {
"use strict";
var MAXLEN=50; /* tweak this */
var MINLEN=20;
function genString() {
var array = new Uint8Array(MAXLEN);
window.crypto.getRandomValues(array);
var array = Array.apply( [], array ); /* turn into non-typed array */
array = array.filter(function(x) {
/* strip non-printables: if we transform into desirable range we have a propability bias, so I suppose we better skip this character */
return x > 32 && x < 127;
});
return String.fromCharCode.apply(String, array);
}
var tmp = genString();
while (tmp.length < MINLEN) {
/* unlikely too loop more than once.. */
tmp += genString(); } prompt("",tmp);
})();
@jaxley
Copy link

jaxley commented Jul 20, 2018

Pretty nice. I wanted to constrain to characters that didn't include so many symbols but avoided bias by keeping the set to 64 (128 bits % 64 == 0):

A-Za-z0-9@-

Changed the array to Uint16Array to get 128 bits and the filter to return r===45 || r>=47&&r<=57 || r>=64&&r<=90 || r>=97&&r<=122

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment