Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate a secure password in javascript

What's the quickest way to generate a secure password in javascript?

I want it to contain at least 1 special character, and 2 mixed case. Must be at least 6 characters long.

like image 255
chovy Avatar asked Sep 28 '12 07:09

chovy


People also ask

How does react JS generate random password?

Using the State from React JSconst generatePassword = () => { // Create a random password const randomPassword = Math. random(). toString(36).

How do I get a random password in Nodejs?

You'll need to create another function that uses the length parameter to slice the password down to the required length with proper randomization. For this, I used the following code snippet: const generatePassword = (length, chars) => { let password = ""; for (let i = 0; i < length; i++) { password += chars.


1 Answers

Here are some useful String functions:

String.prototype.pick = function(min, max) {
    var n, chars = '';

    if (typeof max === 'undefined') {
        n = min;
    } else {
        n = min + Math.floor(Math.random() * (max - min + 1));
    }

    for (var i = 0; i < n; i++) {
        chars += this.charAt(Math.floor(Math.random() * this.length));
    }

    return chars;
};


// Credit to @Christoph: http://stackoverflow.com/a/962890/464744
String.prototype.shuffle = function() {
    var array = this.split('');
    var tmp, current, top = array.length;

    if (top) while (--top) {
        current = Math.floor(Math.random() * (top + 1));
        tmp = array[current];
        array[current] = array[top];
        array[top] = tmp;
    }

    return array.join('');
};

Your password would look like this:

var specials = '!@#$%^&*()_+{}:"<>?\|[];\',./`~';
var lowercase = 'abcdefghijklmnopqrstuvwxyz';
var uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var numbers = '0123456789';

var all = specials + lowercase + uppercase + numbers;

var password = '';
password += specials.pick(1);
password += lowercase.pick(1);
password += uppercase.pick(1);
password += all.pick(3, 10);
password = password.shuffle();

Demo: http://jsfiddle.net/Blender/ERCsD/6/

like image 198
Blender Avatar answered Sep 30 '22 14:09

Blender