Skip to content

Instantly share code, notes, and snippets.

@jaxley
Forked from mozfreddyb/random_string.js
Created July 20, 2018 17:29
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 jaxley/6a2dc576f327ccc5544ecaa0cc1507f5 to your computer and use it in GitHub Desktop.
Save jaxley/6a2dc576f327ccc5544ecaa0cc1507f5 to your computer and use it in GitHub Desktop.
generate random strings, e.g., for passwords
/*
A function to generate secure random 16-32 character passwords in your browser, using the character set
A-Za-z0-9@-
*/
/*
in one line for bookmarkletts:
javascript:!function(){"use strict";function r(){var r=new Uint16Array(n);window.crypto.getRandomValues(r);var r=Array.apply([],r);return r=r.filter(function(r){return r===45 || r>=47&&r<=57 || r>=64&&r<=90 || r>=97&&r<=122}),String.fromCharCode.apply(String,r)}for(var n=32,t=16,a=r();a.length<t;)a+=r();prompt("",a)}();
*/
(function() {
"use strict";
var MAXLEN=32; /* tweak this */
var MINLEN=16;
function genString() {
var array = new Uint16Array(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 r===45 || r>=47&&r<=57 || r>=64&&r<=90 || r>=97&&r<=122;
});
return String.fromCharCode.apply(String, array);
}
var tmp = genString();
while (tmp.length < MINLEN) {
/* unlikely too loop more than once.. */
tmp += genString(); } prompt("",tmp);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment