A Comprehensive Guide to Encryption and Password Hashing in Laravel 10

Spread the love

Laravel 10: Security is a top priority in the world of web development. We are entrusted with sensitive user data as developers, which we must safeguard. Laravel, a popular PHP framework, has robust and simple encryption and hashing techniques by default. This post will provide a detailed guide to understanding and applying these Laravel security features. We’ll look at the nuances of Laravel’s encryption mechanisms, password hashing, and how to use these capabilities efficiently in your projects. Whether you’re a seasoned Laravel developer or just getting started, this article will teach you how to construct more secure online apps using Laravel.

1. Installation of Laravel 10

Laravel 10 is a PHP framework that is simple to install and configure on your local development environment. Laravel 10 is most commonly installed via Composer, a PHP dependency management tool.

composer global require laravel/installer

or you can create a new Laravel project using the Laravel cli

laravel new project-name

Finally you can start your Laravel application using the following command

cd project-name
php artisan serve

2. Configuration of Laravel and the Importance of the Encryption Key

Configuration files in Laravel 10 are kept in the "config" directory. Sensitive data, such as "database credentials", "encryption keys", and "API keys", are kept in a special file called ".env", which is located at the root of your Laravel project.

The ".env" file is critical for your Laravel 10 application’s security. It contains the variable "APP_KEY", which is Laravel’s encryption key. The "Illuminate\Encryption\Encrypter" class uses this key, which should be a random 32 character string. All encrypted values will be insecure unless this key is properly set.

Consider the following scenario. Assume you’re creating a blog application with Laravel. You want to protect the security of user data and blog content. Here’s how you’d configure your ".env" file:

2.1. After installing Laravel 10, navigate to your project directory and open the ".env" file. 2.2. Look for the variable "APP_KEY". If it is not present or is not a 32-character string, you must create a new key. 2.3. Open your terminal, navigate to your project directory, and enter the following command to generate a new key:

php artisan key:generate

This command will generate a new random key and automatically update the 'APP_KEY' variable in your ".env" file.

2.4. Save and close your ".env" file. Your Laravel application is now protected by an encryption key!

3. Encryption in Laravel

The "encryptor" class in Laravel uses "OpenSSL" to offer "AES-256" and "AES-128" encryption. You can use the "encrypt" function to encrypt a value and the "decrypt" function to decrypt it.

Continuing with our blog application example, assume you wish to save a blog post draft. However, you want to encrypt this document so that even if someone acquires unauthorized access to your database, they cannot see the draft text.

Here’s how you’d go about it:

3.1. To encrypt the draft content, you would use the encrypt function:

$encryptedDraft = encrypt($draftContent);

The content of your draft blog post is represented by "$draftContent" in this code. The "encrypt" function will return an encrypted version of this content, which will be saved in the "$encryptedDraft" variable.

3.2. You can then store "$encryptedDraft" in your database.

3.3. When you want to read the draft content, you would use the "decrypt" function:

$decryptedDraft = decrypt($encryptedDraft);

The encrypted draft content collected from your database is represented by "$encryptedDraft" in this code. The "decrypt" function will return the draft’s original content, which is kept in "$decryptedDraft".

4. Hashing in Laravel

Laravel includes a "Hash" facade for secure "Bcrypt" hashing of user passwords. This facade provides three main functions: 'make', "check", and "needsRehash".

Continuing with our blog application example, imagine you’re adding a user registration function. Here’s how you’d put Laravel’s hashing methods to use.

4.1. When a new user registers, you would use the make function to hash their password before storing it in your database.

$hashedPassword = Hash::make($password);

"$password" is the plain-text password provided by the user during registration in this code. The "make" function will return a hashed version of this password, which will be saved in the variable "$hashedPassword".

4.2. You can then store $hashedPassword in your database.

4.3. When the user logs in, you would use the check function to verify their password:

if (Hash::check($plainTextPassword, $hashedPassword)) {
    // The passwords match...
}

In this code, "$plainTextPassword" represents the plain-text password entered by the user at login, and "$hashedPassword" represents the hashed password obtained from your database. If the plain-text password matches the hashed password, the check function returns true.

4.4. When upgrading passwords, use the "needsRehash" function to determine whether the hashed password should be rehashed.

if (Hash::needsRehash($hashedPassword)) {
    $hashedPassword = Hash::make($plainTextPassword);
}

"$hashedPassword" is the previously hashed password in this code. If the password must be rehashed (for example, due to a change in your application’s hashing configuration), the "needsRehash" method will return true, and you can then rehash it.

5. Creating User Model

A "model" in Laravel is a PHP class that allows us to specify the ‘logic’ of our data. It is where you will "retrieve", "insert", and "update" data from your database table. To manage user data in our blog application, we’ll need a User model.

5.1. Laravel has an Artisan command-line utility for creating new models. Navigate to your project directory in your terminal and perform the following command.

php artisan make:model User -m

The -m option tells Artisan to create a new database migration file for the User model.

5.2. This command will create two new files: "app/User.php" (the User model) and "database/migrations/xxxx_xx_xx_xxxxxx_create_users_table.php" (the migration file). The exact name of the migration file will depend on the date and time you created it.

5.3. After that, open the migration file. You can specify the structure of your database’s users table here. You might want columns for id, name, email, password, and remember_token, for example.

5.4. Navigate to the "app/User.php" file. You can specify the properties your User model should allow mass assignment, such as name, email, etc.

5.5. After you’ve specified your table structure in the migration file, use the following command to create the users table in your database.

php artisan migrate

6. Storing Passwords

When a new user registers in our blog application, we need to save their password in our database. However, maintaining plain-text passwords poses a significant security risk. These credentials could be seen and misused if an unauthorized individual gains access to our database. As a result, we must hash the passwords before saving them.

6.1. To hash the password, use the Hash facade’s make function in your registration form handling code (often in a controller)

$hashedPassword = Hash::make($request->password);

6.2. You can then create a new User instance and store it in your database:

$user = new User;

$user->name = $request->name;
$user->email = $request->email;
$user->password = $hashedPassword;

$user->save();

7. Authenticating Users

When a person attempts to log in to our blog application, we need to check their password. This is accomplished by comparing the hashed password stored in our database to the hash of the password entered on login.

7.1. In your login form handling code (usually in a controller), you would use the Hash facade’s check function to verify the password.

if (Hash::check($request->password, $user->password)) {
    // The passwords match...
}

7.2. If the check function returns true, you can log in the user and redirect them to their dashboard or another page.

if (Hash::check($request->password, $user->password)) {
    // The passwords match...
    Auth::login($user);

    return redirect(route('dashboard'));
}

8. Updating Passwords

When a user wants to change their password in our blog application, we must hash the new password and save it in our database. Laravel, on the other hand, adds an extra degree of protection with the "needsRehash" function. This function determines whether the hashed password should be rehashed using the current hashing algorithm and cost factor.

8.1. In your password update form handling code (usually in a controller), you would first verify the user’s current password using the check function.

if (Hash::check($request->currentPassword, $user->password)) {
    // The passwords match...
}

8.2. If the check function returns true, you can then hash the new password using the make function:

if (Hash::check($request->currentPassword, $user->password)) {
    // The passwords match...
    $hashedNewPassword = Hash::make($request->newPassword);
}

8.3. Finally, you can store $hashedNewPassword in your database:

if (Hash::check($request->currentPassword, $user->password)) {
    // The passwords match...
    $hashedNewPassword = Hash::make($request->newPassword);

    $user->password = $hashedNewPassword;
    $user->save();
}

Always use Laravel’s built-in utilities to hash and verify passwords. Never directly compare or store plain-text passwords.

Conclusion

In our journey of Laravel’s encryption and hashing mechanisms, we’ve seen how these built-in capabilities provide strong security when dealing with sensitive data. Whether you’re building a simple blog or a complex e-commerce business, Laravel provides the tools you need to secure data security.

Keep in mind that security is an ongoing duty. Keep up with the newest practices and keep your Laravel application up to date to take advantage of the latest security fixes. We hope you found this article useful in your journey as a Laravel developer.

For those looking to delve deeper into the advanced features of Laravel, I highly recommend the article “Mastering Laravel Macros: A Comprehensive Guide“. This comprehensive guide provides an in-depth exploration of Laravel Macros, a powerful feature that allows you to add methods to classes on-the-fly. It’s an excellent read for anyone keen on taking their Laravel skills to the next level.

Have fun coding!