php doubts how to generate ten random passwords

1

Hello, I have this code that is similar to what I want. good it generate number from 1 to 10 and sequence type:
1
2
and there goes.

I would like instead of the number, it would generate random type passwords:
w3e4r5
g6t5e4 Home so it goes

<?php 
for ($x = 1; $x <= 10; $x++) {
    echo "$x";
} 
?>
    
asked by anonymous 06.03.2017 / 02:23

3 answers

3

PHP 7 has a function called random_bytes that you use by converting from binary to hex, generates a string similar to what you want.

<?php
// Usando a função random_bytes do PHP 7
for ($x = 1; $x <= 10; $x++) 
{
    echo bin2hex(random_bytes(3)) . "<br>"; // gera uma string pseudo-randômica criptograficamente segura de 6 caracteres
} 
?>

Output example (changes every time you run the script):

eb5a35
ce5121
d5c514
e4eec4
48d781
52367c
ae39cd
5ef0ff
dfe681
0ac13f

Reference: link

But if you still do not use PHP7 or you did not like the hexadecimal option used by the existing function in PHP7, an interesting technique I saw in Stack Overflow in English and adapted here is using str_shuffle , a function that shuffles strings randomly. This function is present in PHP from PHP 4 .

<?php


// Usando str_shuffle (mistura strings aleatoriamente)
for ($x = 1; $x <= 10; $x++) 
{

    //Inclua todos os caracteres que gostaria que aparecessem nas strings geradas
    $caracteres_q_farao_parte = 'abcdefghijklmnopqrstuvwxyz0123456789';

    $password = substr( str_shuffle($caracteres_q_farao_parte), 0, 6 );     

    echo $password . "<br>";

} 


?>

Output example (will come out different every time the script is run):

yc7dj6
g57rt0
prwgdn
hctvog
d2l0cq
r78fp1
0z6c4e
95m8fa
19bnx5
vyw8p6

Reference: link

    
06.03.2017 / 04:20
3

If you really care about " exaggeratedly" "you should safely use LibSodium , he it has both features, to generate and to convert to hexadecimal, I'm answering this based on what I replied here .

for($gerar = 10; $gerar > 0; $gerar--){
    echo \Sodium\bin2hex( \Sodium\randombytes_buf(3) );
}

The original% of PHP, as responded by @Antonio Alexandre, is vulnerable to side-channel attacks, while bin2hex is more resistant and this type of attack.

>     
06.03.2017 / 05:10
0

Here is a solution

     function randomPassword() {
        $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
        $pass = array(); 
        $alphaLength = strlen($alphabet) - 1; 
        for ($i = 0; $i < 8; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        return implode($pass); 
    }

  for ($x = 1; $x <= 10; $x++) {
      echo randomPassword() .'<br>';
    }
    
06.03.2017 / 03:26