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.
Using the State from React JSconst generatePassword = () => { // Create a random password const randomPassword = Math. random(). toString(36).
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With