Friday, 3 November 2017

How to generate a not totally crap password in Javascript

I keep writing versions of this in various languages and then losing them. I'm posting it here so I'll have a version I can run in my browser whenever I need a new password for something. The password generated will often be harder to guess than one I would just make up, but that's the only guarantee I'm giving.
function password(n) {
    if (n < 3) n = 3;
    let randomIndex=0;
    const randomArray = new Uint32Array((n << 1) - 1);
    window.crypto.getRandomValues(randomArray);
    const random = n => randomArray[randomIndex++] % n;
    const randOf = s => s.charAt(random(s.length));
    const shuffle = (s) => {
        let c = [...s];
        let n = c.length;
        for(let i = n - 1; i > 0; i--){
            let j = random(i + 1);
            let tmp = c[i];
            c[i]  = c[j];
            c[j]  = tmp;
        }
        return c;
    };
    
    let a=[];
    for(let i=0;i<n-3;i++){
        a.push(randOf("abcdefghijklmnopqrstuvwxyz"));
    }
    a.push(randOf("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
    a.push(randOf("01234567890"));
    a.push(randOf("!\"£$%^&*()-_+=[]{}:;@'~#<>,./?"));
    return shuffle(a).join("");
}