str_shuffle and randomness

前端 未结 3 569
广开言路
广开言路 2020-12-01 09:24

A while back I wrote a random string generator that builds a string using the mt_rand()th character in a string until the desired length is reached.

public         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 10:12

    Still not cryptographically secure, but here is a way to use str_shuffle() while allowing character repetition, thereby improving complexity...

    generate_password($length = 8, $strength = 3) {
        if ($length < 6) $length = 6;
        if ($length > 32) $length = 32;
        // Excludes [0,O,o,1,I,i,L,l,1] on purpose for readability
        $chars = 'abcdefghjkmnpqrstuvwxyz';
        if ($strength >= 2) $chars .= '23456789';
        if ($strength >= 3) $chars .= strtoupper($lower);
        if ($strength >= 4) $chars .= '!@#$%&?';
        return substr(str_shuffle(str_repeat($chars, $length)), 0, $length);
    }
    

    $chars is repeated $length times before the string is shuffled to make this a little better than shuffling only single occurrence.

    We only use this in systems that do not store sensitive information ;)

提交回复
热议问题