Security Tip: Laravel's Password Generator

[Tip#37] If you need to generate passwords in your app, it's important to use a cryptographically secure algorithm. Laravel makes this easy by giving us the Str::password() helper!

Security Tip: Laravel's Password Generator

When generating new passwords, you need an algorithm that uses a cryptographically secure random generator (as per Security Tip: Cryptographically Secure Randomness) to ensure there is enough entropy to keep your passwords unguessable. A good way to do this is to generate lengthy passwords with a significant character set that includes lower case and uppercase letters, numbers, and extra symbols.

🤓
Entropy: A fancy word used to discuss how guessable a password is. The more entropy it has, the harder it is to guess. It’s roughly equivalent to how many characters it could include and how long it is, but there is a lot of nuance and complexity that we don’t have time to go into here.

Laravel’s Password helper lets you do exactly that:

Str::password($length = 32, $letters = true, $numbers = true, $symbols = true, $spaces = false): string;

By default, the helper will return a 32 character incredibly secure password:

> $password = Str::password();
= "eY-j4B<kLf%o/k~x*#&9KUHPU8~!;I?8"

You can change the length, toggle on/off letters, numbers, symbols, and spaces:

> $password = Str::password(
      length:  16, 
      letters: true, 
      numbers: false, 
      symbols: true, 
      spaces:  true
  );
= "$*|[# S*?/Qxj~W,"

Internally it uses random_int() to securely build the password from it’s extensive character list, so it can be considered cryptographically secure.

So the next time you need to generate a password in your app, you can reach straight for Str::password().

Update (2024-05-09)

Since writing this article, I have built my own Random package, which offers an alternative to generating cryptographically secure passwords, but with more flexibility around character sets, etc. Check it out if Str::random() doesn't meet your needs: https://github.com/valorin/random.


🕵️
Worried about your app being hacked? Book in a Laravel Security Audit and Penetration Test! I can find the vulnerabilities before a hacker does, and help you fix them!
🥷
Learn to Think Like a Hacker with my hands-on practical security course: Practical Laravel Security!