PHP – generate secure password

This post will be very short. We must sometimes generate random password in PHP – for example when users create accounts on our service, or we send them new password after reset. Yes, we can do this in many ways, but most of them are bad solutions – we can create function (or method, class) to generate random string from given range, do it manually and try to make all random. But it isn’t random – it must by real secure, we must  use cryptographically secure pseudorandom generator.

Solution is very simple. We can use random_bytes function. It is secure. And we can chhose generated random string length:

// Return 10-length password
$randomPassword = bin2hex(random_bytes(5)); 

And… it’s all. Really. You should not create your custom functions because it isn’t secure. This method is very simple and secure.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Martin Grossmann
Martin Grossmann
2 years ago

It’s important to say, that this code returns only a lowercase string, containing only numbers and letters a-f. So it’s not really as good to use only this as a password generator.
I suggest to take a look at Nette\Utils\Random, where you can generate a cryptographically secure random string https://github.com/nette/utils/blob/master/src/Utils/Random.php

wariat
wariat
1 year ago

what about:
$randomPassword = substr( password_hash( ‘dupa.8’, PASSWORD_DEFAULT ), 5, 10 );

;-)