116 votes

Générer une chaîne de mots de passe aléatoire avec des exigences en javascript

Je veux générer une chaîne aléatoire qui doit comporter 5 lettres de a à z et 3 chiffres.

Comment puis-je faire cela avec JavaScript ?

J'ai le script suivant, mais il ne répond pas à mes exigences.

        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        var string_length = 8;
        var randomstring = '';
        for (var i=0; i<string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            randomstring += chars.substring(rnum,rnum+1);
        }

7 votes

S'il répond à votre exigence, quelle est la question alors ? En outre, votre exigence de mot de passe forcé est une mauvaise idée.

8 votes

4 votes

new Array(12).fill().map(() => String.fromCharCode(Math.random()*86+40)).join("") Une solution astucieuse pour produire un mot de passe de 12 caractères avec des caractères spéciaux, des chiffres supérieurs et inférieurs, dans une approche très légère.

0voto

Caiuby Freitas Points 11

Vous pouvez toujours utiliser l'objet window.crypto disponible dans la version récente du navigateur.

Il suffit d'une ligne de code pour obtenir un nombre aléatoire :

let n = window.crypto.getRandomValues(new Uint32Array(1))[0];

Il permet également de crypter et de décrypter les données. Plus d'informations sur MDN Web docs - window.crypto .

0voto

var Password = {

  _pattern : /[a-zA-Z0-9_\-\+\.]/,

  _getRandomByte : function()
  {
    // http://caniuse.com/#feat=getrandomvalues
    if(window.crypto && window.crypto.getRandomValues) 
    {
      var result = new Uint8Array(1);
      window.crypto.getRandomValues(result);
      return result[0];
    }
    else if(window.msCrypto && window.msCrypto.getRandomValues) 
    {
      var result = new Uint8Array(1);
      window.msCrypto.getRandomValues(result);
      return result[0];
    }
    else
    {
      return Math.floor(Math.random() * 256);
    }
  },

  generate : function(length)
  {
    return Array.apply(null, {'length': length})
      .map(function()
      {
        var result;
        while(true) 
        {
          result = String.fromCharCode(this._getRandomByte());
          if(this._pattern.test(result))
          {
            return result;
          }
        }        
      }, this)
      .join('');  
  }    

};

<input type='text' id='p'/><br/>
<input type='button' value ='generate' onclick='document.getElementById("p").value = Password.generate(16)'>

0voto

Sadhana Rajan Points 11

Générer un mot de passe aléatoire de 8 à 32 caractères avec au moins 1 minuscule, 1 majuscule, 1 chiffre, 1 spl char (!@$&)

    function getRandomUpperCase() {
       return String.fromCharCode( Math.floor( Math.random() * 26 ) + 65 );
    }

    function getRandomLowerCase() {
       return String.fromCharCode( Math.floor( Math.random() * 26 ) + 97 );
    } 

    function getRandomNumber() {
       return String.fromCharCode( Math.floor( Math.random() * 10 ) + 48 );
    }

    function getRandomSymbol() {
        // const symbol = '!@#$%^&*(){}[]=<>/,.|~?';
        const symbol = '!@$&';
        return symbol[ Math.floor( Math.random() * symbol.length ) ];
    }

    const randomFunc = [ getRandomUpperCase, getRandomLowerCase, getRandomNumber, getRandomSymbol ];

    function getRandomFunc() {
        return randomFunc[Math.floor( Math.random() * Object.keys(randomFunc).length)];
    }

    function generatePassword() {
        let password = '';
        const passwordLength = Math.random() * (32 - 8) + 8;
        for( let i = 1; i <= passwordLength; i++ ) {
            password += getRandomFunc()();
        }
        //check with regex
        const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,32}$/
        if( !password.match(regex) ) {
            password = generatePassword();
        }
        return password;
    }

    console.log( generatePassword() );

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X