Aerendir
Aerendir

Reputation: 6389

Symfony 2 Util SecureRandom and "null" character: how to manage it

To generate random passwords in my application I'd like to use the Symfony Random generator component.

The documentation says this about the possibility of a null character (\0):

The nextBytes() method returns a binary string which may contain the \0 character. This can cause trouble in several common scenarios, such as storing this value in a database or including it as part of the URL. The solution is to hash the value returned by nextBytes() (to do that, you can use a simple md5() PHP function).

So, my question is: if the method returns a nullchar, then the User will have to use it to write his password.

How can I deal with this, as I can't figure out how a null char can be write into a login form. Or am I missing something in the thought?

Upvotes: 1

Views: 236

Answers (1)

user4545769
user4545769

Reputation:

You should never use the SecureRandom utility to generate passwords - it only ever generates bytes rather than characters (and even if you used the bytes as characters, half the ASCII character map are difficult to enter using a keyboard).

You could in theory use base64_encode on the data supplied by SecureRandom to generate a string that is enterable on a keyboard.

If you definitely want to generate random passwords then you're better off defining a corpus of characters you want to use then using something like mt_rand to get key offsets. E.g.

$corpus = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
$password = '';
for ($i = 0; $i < $passwordLength; i++) {
    $password .= $corpus[ mt_rand(0, (count($corpus) - 1)) ];
}

return $password;

These won't be "secure" random passwords but then that leads into a larger discussion about security policy and changing passwords etc.

Upvotes: 2

Related Questions