Encryption in Laravel 10: Full Guide

Chimeremze Prevail Ejimadu
5 min readApr 4, 2023

--

Photo by Markus Spiske on Unsplash

Welcome to the exciting world of Laravel 10 encryption! If you’re a developer, you know that keeping user data secure is no laughing matter. If you’re not taking the necessary steps to secure your users’ information, you’re putting them and your company at risk. But fear not, dear reader! With Laravel 10’s encryption capabilities, you can fortify your applications and shield your data from the nefarious characters lurking in the shadows of the internet. In this full guide, we’ll take a deep dive into how to encrypt API tokens, explore the many use cases for encryption in Laravel, and show you how to build a fortress around your data.

Encryption is the process of converting plaintext into a cipher text, which is unreadable unless decrypted with the right key. There are many methods used in encrypting data, but we’ll focus on laravel’s default encryption mechanism.

Laravel’s encryption services provide a simple, convenient interface for encrypting and decrypting text via OpenSSL using AES-256 and AES-128 encryption. All of Laravel’s encrypted values are signed using a message authentication code (MAC) so that their underlying value can not be modified or tampered with once encrypted.

— Laravel Docs

How can we use Laravel Encrypter?

There are two ways to encrypt and decrypt:

//Encryption
use Illuminate\Support\Facades\Crypt;

.....

Crypt::encryptString($value);




//Decrption
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Crypt;

try {
$decrypted = Crypt::decryptString($encryptedValue);
} catch (DecryptException $e) {
// ...
}

The other way — Using laravel global helpers:

encrypt($value)

decrypt($encryptedValue)

What we are going to build:

We will build a simple Laravel 10 application that allows users to generate API tokens. We will then encrypt the tokens and store them in the database. When a user sends a request to the API, we will decrypt the token and use it to authenticate the user.

How to build it:

Create a new Laravel 10 application using composer. Run the following command in your terminal to create a new Laravel project.

composer create-project --prefer-dist laravel/laravel laravel-encryption

Create a new migration file to create the tokens table. Run the following command in your terminal.

php artisan make:migration create_tokens_table --create=tokens

Edit the newly created migration file to define the columns for the tokens table. Add the following code to the up method of the migration file.

Schema::create('tokens', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('token');
$table->timestamps();
});

Run the migration to create the tokens table. Run the following command in your terminal.

php artisan migrate

Create a new API token controller using the following command in your terminal.

php artisan make:controller ApiTokenController --api

In the ApiTokenController, add a new method called generateToken that generates a new API token for the user. Add the following code to the ApiTokenController.

public function generateToken(Request $request)
{
$token = Str::random(60);
Token::create([
'name' => $request->name,
'token' => encrypt($token)
]);
return response()->json([
'token' => $token
]);
}

In the Token model, add a mutator to decrypt the token when it is retrieved from the database. Add the following code to the Token model.

class Token extends Model
{
// ...
public function getTokenAttribute($value)
{
return decrypt($value);
}
// ...
}

Add a new API route to the routes/api.php file that maps to the generateToken method in the ApiTokenController. Add the following code to the routes/api.php file.

Route::post('/tokens', [ApiTokenController::class, 'generateToken']);

Test the API by sending a POST request to the /tokens endpoint. The response should include a JSON object with the newly generated token.

Now that we’ve covered how to encrypt API tokens in Laravel 10, let’s explore some of the use cases for encryption in Laravel.

10 Use Cases for Encrypting in Laravel

  1. Protecting User Data: Encryption is an effective way to protect sensitive data like passwords, credit card information, and personal identification numbers. Laravel offers a number of encryption methods to ensure that user data is kept safe from unauthorized access.
  2. Securing Cookies: Cookies can contain sensitive information such as user preferences and session data. Laravel’s encryption features can be used to secure this data and prevent unauthorized access.
  3. Securing API Requests: APIs are a popular way for applications to communicate with each other. Laravel’s encryption features can be used to secure the data that is being transferred between the two applications.
  4. Securing Passwords: Passwords are a common target for hackers. Laravel provides a secure way to store and manage passwords using encryption.
  5. Protecting Intellectual Property: Companies often have intellectual property that needs to be protected. Laravel’s encryption features can be used to protect this information and prevent unauthorized access.
  6. Preventing SQL Injection: SQL injection attacks can be used to gain unauthorized access to a database. Laravel’s encryption features can be used to prevent SQL injection attacks by encrypting user input before it is sent to the database.
  7. Securing File Systems: Encryption can also be used to secure files stored on a file system. Laravel provides features to encrypt files and ensure that they are only accessible to authorized users.
  8. Protecting Sensitive Configuration Information: Configuration information such as API keys and passwords can be encrypted to prevent unauthorized access.
  9. Securing Emails: Emails can contain sensitive information such as login credentials or personal information. Laravel’s encryption features can be used to secure emails and prevent unauthorized access.
  10. Protecting Health Information: Health information is highly sensitive and needs to be protected. Laravel’s encryption features can be used to protect health information and prevent unauthorized access.

Conclusion

In conclusion, encryption is an important aspect of web development and can be used to protect sensitive information from unauthorized access. Laravel provides a number of encryption features that can be used to secure user data, cookies, APIs, passwords, intellectual property, file systems, configuration information, emails, and health information. By using these features, developers can ensure that their applications are secure and user data is protected.

Stay tuned!!! I will be back with some more cool Laravel tutorials in the next article. I hope you liked the article. Don’t forget to follow me 😇 and give some clap 👏. And if you have any questions feel free to comment.

Thank you.

--

--

Chimeremze Prevail Ejimadu

Laravel Developer + Writer + Entrepreneur + Open source contributor + Founder + Open for projects & collaborations. Hit FOLLOW ⤵