Les Snippets

Connexion

Générer un mot de passe aléatoire

Niveau requis pour utiliser/comprendre cette source : 1 ( Débutant )
Créé le 18/05/2008 11:37:02 et initié par swaenboutu [Liste]
Date de mise à jour : 27/08/2008 11:15:09
Vue : 10546
Catégorie(s) : Sécurité, Trucs & Astuces, Chaîne de caractères
Langages dispo pour ce code :
- PHP 3, PHP 4, PHP 5
- PHP 4, PHP 5
- Delphi 5
- Javascript
- VBScript
- VBScript
- VB6, VBA
- VB 2005, VB 2008
- C, C++
- C# 1.x, C# 2.x, C# 3.x



Langage : PHP 3 , PHP 4 , PHP 5
Date ajout : 18/05/2008
Posté par swaenboutu [Liste]
<?php
function Creation_mdp($longueur){
    $elements = array('a','b','c','d','e','f','g','h','j','k','m','n','p','q','r','s','t','u','v',w','x','y','z',
        'A','B','C','D','E','F','G','H','J','K','M','N','P','Q','R','S','T','U','V','W','X','Y','Z',
        '2','3','4','5','6','7','8','9');
    $mdp = NULL;
    $iElementsLength = count($elements);
    for ($i=1; $i <= $longueur; $i++){
            $nbre = rand(0,$iElementsLength);
            $mdp .= $elements[$nbre];
        
        }
    return $mdp;
}
$mdp = Creation_mdp(8);
echo("Le mot de passe est g&eacute;n&eacute;r&eacute;&nbsp:&nbsp;$mdp");
?>
Langage : PHP 4 , PHP 5
Date ajout : 22/05/2008
Posté par f0xi [Liste]
DateMAJ : 05/07/2008
function GenPass($GPlen, $GPmaj, $GPmin, $GPnum) {
  $GPchars = "";
  $GPpass  = "";
  $GPchars = $GPnum ? str_shuffle($GPchars."0123456789") : $GPchars;
  $GPchars = $GPmin ? str_shuffle($GPchars."azertyuiopqsdfghjklmwxcvbn") : $GPchars;
  $GPchars = $GPmaj ? str_shuffle($GPchars."AZERTYUIOPQSDFGHJKLMWXCVBN") : $GPchars;
   $GPlen = ($GPlen < 4) ? 4 : $GPlen;
  $GPpass = substr(str_shuffle($GPchars), rand(1, strlen($GPchars)-$GPlen), $GPlen);
  return($GPpass);
}

Remarque :
GenPass(4, true, false, false) majuscules seulement
GenPass(4, false, true, false) minuscules seulement
GenPass(4, false, false, true) chiffres seulement
GenPass(4, true, true, false) maj+min
GenPass(4, true, false, true) maj+chiffres
GenPass(4, false, true, true) min+chiffres
GenPass(4, true, true, true) maj+min+chiffres

Langage : Delphi 5
Date ajout : 05/07/2008
Posté par f0xi [Liste]
DateMAJ : 05/07/2008
type
    TCharRange = (
     crNumeric, 
     crMinAlpha,
     crMajAlpha 
   );
    TCharRanges = set of TCharRange;
  
  
 function StrShuffle(const S : string): string;
 var I, NI, L : integer;
     pR : PChar;
 begin
   L := length(S);
   SetLength(Result, L);
   pR := PChar(Result);
   FillChar(pR^, L, #0);
   for I := 1 to L do
   begin
     repeat
       NI := random(L);
     until pR[NI] = #0;
     pR[NI] := S[I];
   end;
 end;
 
 
 { GenPassword
   
   Génère un mot de passe aléatoire.
 
   Paramètres :
     LN [I] entier, taille du mot de passe a générer
     CR [I] TCharRanges, type de caractères présent dans le mots de passe
 
   Retour :
     Chaine, mot de passe généré.
 }
 function GenPassword(const LN: integer; const CR: TCharRanges = [crNumeric, crMinAlpha]): string;
 var safeCR : TCharRanges;
    safeLN : integer;
    spwd : string;
    lpwd : integer;
begin
  spwd := '';
  lpwd := 0;
  safeCR := CR;
  if safeCR = [] then
    safeCR := [crNumeric, crMinAlpha];
  safeLN := LN;
  if safeLN = 0 then
    safeLN := 8;
  if crNumeric in safeCR then
  begin
    spwd := StrShuffle('09182736455463728190');
    inc(lpwd,20);
  end;
  if crMinAlpha in safeCR then
  begin
    spwd := StrShuffle(spwd+'lmnopqrstuvwxyzabcdefghijk');
    inc(lpwd,26);
  end;
  if crMajAlpha in safeCR then
  begin
    spwd := StrShuffle(spwd+'HIJKLMNOPQRSTUVWXYZABCDEFG');
    inc(lpwd,26);
  end;
  result := copy(StrShuffle(spwd), random(lpwd)-SafeLN, SafeLn);
end;
Langage : Javascript
Date ajout : 29/07/2008
Posté par dvdstory [Liste]
function string_generator(nb_caract) {
var chaine = Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9');
var pass = '';
var nb, u;
for (u=1; u <= nb_caract; u++) {
nb = chaine.length;
nb = Math.round(Math.random()*chaine.length);
pass += chaine[nb];
}
return pass;
}

Langage : VBScript
Date ajout : 29/07/2008
Posté par MisterWhiteLapin [Liste]

' Forcer la déclaration des variables.
Option Explicit
' Nous utilisons de l'aléa donc nous faisons appel à Randomize au
' début du script pour avoir un meilleur aléa.
Randomize
' Déclaration de la variable contenant tous les
'caractères potentienles du mot de passe.
Dim strElmts
' Nombre d'éléments (de caractères différents
'composants possible pour le mot de passe).
Dim intNbElmts

' C'est  ici qu'il faut ajouter/enlever des
' caractères selon ses attentes.
strElmts = "abcdefghijklmnopqrstuvwxyz" & _
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ" & _
                "0123456789" & _
                "#?./§,;:!%*$&'<>()[]{}@-_+=|"
intNbElmts = Len(strElmts)

' Génère un mot de passe de intLen caractères.
Function PasswordGeneration(intLen)
    Dim i
    PasswordGeneration = ""
    For i = 1 to intLen
        PasswordGeneration = PasswordGeneration & mid(strElmts, Int(rnd * intNbElmts) + 1, 1)
    Next
End Function
' Vérifie la "politique de sécurité" du mot de passe.
' Ici, la politique de sécurité adoptée est la suivante:
'   - au moins 8 caractères,
'   - au moins 1 caractère en majuscule,
'   - au moins 1 caractère en minuscule,
'   - au moins 1 caractère numérique,
'   - au moins 2 caractères 'spéciaux'.
' Retourne "True" si la politique de sécurité est bonne.
Function CheckSecurityPolitic(strPassword)
    ' Indices de boucle.
    Dim i, j
    ' Compteurs.
    Dim intCptMinuscules, intCptMajuscules, intCptNum, intCptSpec
    ' Index de début de séquence de caractère spéciaux
    ' dans la variable strElmts.
    Dim intIndexSpec
    ' Taille du mot de passe.
    Dim intLenPassword
    intLenPassword = Len(strPassword)
    ' vérification de "au moins 8 caractères":
    If (intLenPassword < 8) Then
        CheckSecurityPolitic = False
        Exit Function
    End If
    ' ATTENTION: Il faut que la séquences de caractères "spéciaux"
    ' commence par # (comme c'est le cas ici).
    intIndexSpec = InStr(strElmts, "#")
    ' Comptage des caractères.
    intCptMinuscules = 0
    intCptMajuscules = 0
    intCptNum = 0
    intCptSpec = 0
    For i = 1 To intLenPassword
        If ((asc(Mid(strPassword, i, 1)) >= asc("a")) And _
            (asc(Mid(strPassword, i, 1)) <= asc("z"))) Then
            intCptMinuscules = intCptMinuscules + 1
        End If
        If ((asc(Mid(strPassword, i, 1)) >= asc("A")) And _
            (asc(Mid(strPassword, i, 1)) <= asc("Z"))) Then
            intCptMajuscules = intCptMajuscules + 1
        End If
        If ((asc(Mid(strPassword, i, 1)) >= asc("0")) And _
            (asc(Mid(strPassword, i, 1)) <= asc("9"))) Then
            intCptNum = intCptNum + 1
        End If
        For j = intIndexSpec To intNbElmts
            If (Mid(strElmts, j, 1) = Mid(strPassword, i, 1)) Then
            intCptSpec = intCptSpec + 1
        End If
        Next
    Next
    CheckSecurityPolitic = (intCptMinuscules >= 1) And _
                           (intCptMajuscules >= 1) And _
                           (intCptNum >= 1) And _
                           (intCptSpec >= 2)
End Function

' Génère un mot de passe "sécurisé" de 8 à 14 caractères.
Function SecurityPasswordGeneration()
    SecurityPasswordGeneration = ""
    While (Not (CheckSecurityPolitic(SecurityPasswordGeneration)))
        SecurityPasswordGeneration = PasswordGeneration(Int(rnd * 9) + 6)
    WEnd
End Function

'#####################################
' Tests/démonstrations des fonctions.
'#####################################
Dim strAccumul
' Fonction PasswordGeneration
strAccumul = "Mot de passe condition particulière:" & VbCrlf
strAccumul = strAccumul & "    De 8 caractères:" & PasswordGeneration(8) & VbCrlf
strAccumul = strAccumul & "    Entre 6 et 12 caractères: " & PasswordGeneration(Int(rnd * 6) + 7) & VbCrlf
strAccumul = strAccumul & VbCrlf

' Fonction CheckSecurityPolitic
Dim arrTestPassword
Dim strTestPassword
arrTestPassword = Array("salut", "Salut1664", "<Salut1664>", "*!Rocky4%*", _
                        PasswordGeneration(Int(rnd * 5) + 7), PasswordGeneration(Int(rnd * 5) + 7), _
                        PasswordGeneration(Int(rnd * 5) + 7), PasswordGeneration(Int(rnd * 5) + 7))
For Each strTestPassword In arrTestPassword
    If CheckSecurityPolitic(strTestPassword) Then
        strAccumul = strAccumul & "Le mot de passe: " & strTestPassword & _
                                  " est conforme à la politique de sécurité :-)" & VbCrlf
    Else
        strAccumul = strAccumul & "Le mot de passe: " & strTestPassword & _
                                   " n'est pas conforme à la politique de sécurité :-(" & VbCrlf
    End If
Next
strAccumul = strAccumul & VbCrlf
' Fonction SecurityPasswordGeneration
strAccumul = strAccumul & "Mot de passe ""sécurisé"": " & SecurityPasswordGeneration() & VbCrlf
strAccumul = strAccumul & "Mot de passe ""sécurisé"": " & SecurityPasswordGeneration()
Msgbox strAccumul & VbCrlf & "       

Remarque :
Voici 3 fonctions en rapport avec le sujet du snippet. Le bout de code qui suit montre une utilisation.
Langage : VBScript
Date ajout : 29/07/2008
Posté par MisterWhiteLapin [Liste]
Function PasswordGeneration(intLen)
    Dim i
    Randomize
    Dim strElmts
    Dim intNbElmts
    strElmts = "abcdefghijklmnopqrstuvwxyz" & _
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ" & _
                "0123456789" & _
                "#?./§,;:!%*$&'<>()[]{}@-_+=|"
    intNbElmts = Len(strElmts)
    PasswordGeneration = ""
    For i = 1 to intLen
        PasswordGeneration = PasswordGeneration & mid(strElmts, Int(rnd * intNbElmts) + 1, 1)
    Next
End Function

Langage : VB6 , VBA
Date ajout : 12/08/2008
Posté par PCPT [Liste]
Function GeneratePassword(ByVal Length As Integer, ByVal UChars As Boolean, ByVal LChars As Boolean, ByVal Numbers As Boolean, Optional ByVal PersonnalChars As String = vbNullString) As  String
'Length             -> taille  désirée
'UChars             -> piocher dans  l'alphabet majuscule
'LChars             ->  piocher dans l'alphabet minuscule
'Numbers            -> piocher dans les  chiffres
'PersonnalChars     -> piocher dans  une série de caractères fournis
'GeneratePassword   -> retourne la chaîne de  résultat
    Dim sChars As String
    Dim As Integer
    
    If Length > Then
        Randomize Timer 'cette ligne peut être appelée juste une fois au démarrage de  l'appli, pas besoin dans la fonction
        sChars = PersonnalChars
        If LChars Then sChars = sChars & "azertyuiopqsdfghjklmwxcvbn"
        If UChars Then sChars = sChars & "AZERTYUIOPQSDFGHJKLMWXCVBN"
        If Numbers Then sChars = sChars & "0123456789"
        
        If LenB(sChars) Then
            GeneratePassword = Strings.Space$(Length)
            For i = To Length - 1
                Mid$(GeneratePassword, i + 1, 1) =  Mid$(sChars, Int((Rnd  * Len(sChars)) + 1), 1)
            Next i
        End If
    End If
End Function

'    ---------------------
'   EXEMPLE  D'UTILISATION
'    ---------------------
Private Sub Command1_Click()
    Me.Cls
    Me.Print GeneratePassword(4TrueFalse, False) '  majuscules seulement
    Me.Print GeneratePassword(4FalseTrue, False) '  minuscules seulement
    Me.Print GeneratePassword(4FalseFalse, True) '  chiffres seulement
    Me.Print GeneratePassword(4TrueTrue, False) ' maj  + Min
    Me.Print GeneratePassword(4TrueFalse, True) ' maj  + chiffres
    Me.Print GeneratePassword(4FalseTrue, True) ' Min  + chiffres
    Me.Print GeneratePassword(4TrueTrue, True, "*@<>"' maj + Min + chiffres + persos
End Sub

Langage : VB 2005 , VB 2008
Date ajout : 17/08/2008
Posté par gillardg [Liste]
DateMAJ : 27/08/2008
'''  <summary>
'' Cette fonction crée un mot de  passe de la longueur désirée
'' avec les  caractères choisis
''  </summary>
'' <param  name="Length">Taille désirée</param>
''  <param name="CLower">Alphabet minuscule</param>
'' <param name="CUpper">Alphabet  MAJUSCULE</param>
'' <param  name="CNum">Numéros</param>
'' <param  name="CPerso">série de caractères qui peut être  fournie</param>
''  <returns></returns>
''  <remarks>
'' voir la fonction exemple pour  l'utilisation
''  </remarks>
Public Function CreateRandomPassword(ByVal Length As Integer, ByVal CLower As Boolean, ByVal CUpper As Boolean, ByVal CNum  As Boolean, Optional ByVal CPerso As String = vbNullString) As String
Dim minus As String "abcdefghijkmnopqrstuvwxyz"
Dim majus As String "ABCDEFGHJKLMNOPQRSTUVWXYZ"
Dim numb As String "0123456789"
Dim _allowedChars As String = String.Empty
If CLower Then
    _allowedChars = _allowedChars & minus
End If
If CUpper Then
    _allowedChars = _allowedChars & majus
End If
If CNum Then
    _allowedChars = _allowedChars & numb
End If
_allowedChars = _allowedChars & CPerso
Dim randNum As New Random()
Dim chars(Length - 1As Char
Dim allowedCharCount As Integer = _allowedChars.Length
For As Integer To Length - 1
    chars(i) = _allowedChars.Chars(CInt(Fix((_allowedChars.Length) *  randNum.NextDouble())))
Next i
Return New String(chars)
randNum = Nothing
End Function


'''  <summary>
''' Exemple d'utilisation qui  genere
''' 100 mots de passe et qui en choisit 1  seul au hasard
'''  </summary>
'''  <returns></returns>
Function Exemple() As String
Dim tab(100As String
Dim As Integer
Dim As New Random
For x = To 100
    tab(x) = CreateRandomPassword(10True, True, True, "&|@#§^!°-_$%=+~<>.,;")
Next
Return tab(r.Next(099))
End Function

Langage : C , C++
Date ajout : 19/08/2008
Posté par max12 [Liste]
DateMAJ : 19/08/2008
void GeneratePassword(char* buffer, int length)
{
    char* str = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789";
    srand (time(NULL));
    while(length-- > 0)
        *(buffer++) = str[rand()%62]; //pas strlen pour faire plus rapide
    *(buffer) = 0;
}
//Utilisation
char Buffer[40];
GeneratePassword(Buffer, 7);

Remarque :
Si vous voulez ajouter des caractères n'oubliez pas de remplacer le 62 par le nombre de caractère dans la chaine ou ajoutez strlen en évaluation au début de la fonction.
Langage : C# 1.x , C# 2.x , C# 3.x
Date ajout : 08/12/2008
Posté par Charles Racaud [Liste]
static string GeneratePassword(int Length) {
  return GeneratePassword(Length, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray());
}
static string GeneratePassword(int Length, bool CaseSensitive) {
  if (CaseSensitive)
    return GeneratePassword(Length);
  else
    return GeneratePassword(Length, "0123456789abcdefghijklmnopqrstuvwxyz".ToCharArray());
}
static string GeneratePassword(int Length, char[] Chars) {
  string Password = string.Empty;
  System.Random rnd = new System.Random();
  for (int i = 0; i < Length; i++)
    Password += Chars[rnd.Next(Chars.Length)];
  return Password;
}

Snippets en rapport avec : Aléatoire, Mot, Password, Passe



Codes sources en rapport avec : Aléatoire, Mot, Password, Passe

{Javascript / DHTML} VÉRIFICATION DU NIVEAU DE SÉCURITÉ DU MOT DE PASSE
Cette source est una adaptation du source http://www.csharpfr.com/code.aspx?ID=36129 en javascript q...

{PHP} FONCTION QUI GÉNÉRE UN MOT DE PASSE ALÉATOIRE
Cette fonction permet de générer un mot de passe aléatoire d'une taille donnée ($size) Les caract...

{Visual Basic, VB6, VB.NET, VB 2005} CONNEXION PAR MOT DE PASSE GRÂCE À UNE BDD
Bonjour, voici ma première source sur le site ! J'espère que celle-ci pourra aider des gens ! Il ...

{IRC} ALIAS DE GÉNÉRATION DE MOTS DE PASSE ALÉATOIRES
A utiliser avec modération car il faut arriver à se souvenir du code. Le mieux dans le cas d'un nic...

{Visual Basic, VB6, VB.NET, VB 2005} EFFACER LE MOT DE PASSE DES SESSIONS WINDOWS -NE SE FAIT QU A PARTIR D UN COMPTE ADMINISTRATEUR
Je n'ai fait que mettre en forme la source de hodaking ( script seulement) , elle m'a rendu service ...

{Javascript / DHTML} PROTÉGER UNE PAGE PAR MOT DE PASSE
Ce code sert à protéger une page par mot de passe. Méthode 1 Lors de l'ouverture de celle-ci, un...

{C# / C#.NET} GENERATEUR DE MOT DE PASSE
Un générateur de mot de passe pas très complexe. Il accepte trois paramètres : - Nombre - Ponct...

{ColdFusion} GENERER UN MOT DE PASSE ALÉATOIRE
Je trouve ce code simple et modifiable à souhait :-) ...

{ColdFusion} GÉNÉRER DES MOTS DE PASSE ALÉATOIREMENT
...

{Delphi} GÉNÉRER UN MOT DE PASSE ALÉATOIRE
Génération INSTANTANE d'un mot de passe aléatoire de X lettres ...