generate a secure password in javascript

后端 未结 6 2110
暗喜
暗喜 2021-02-02 02:25

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

6条回答
  •  醉酒成梦
    2021-02-02 03:19

    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/

提交回复
热议问题