Laravel Encryption


Laravel Encryption – The Laravel Encryption is used to provide a encryption facility to encrypte the data.


Laravel Encryption.

Let us understand how to use laravel Encryption.

Function:-

There are some followings function available in laravel Encryption.

  • 1. Introduction.
  • 2. Configuration.
  • 3. Using The Encrypter.

1. Introduction.

Laravel encrypter use open source implementation protocol to provide AES-256 and AES-128 encryption. You are stronly encouraged to use laravel built in encryption and not attempt to roll your own encryption algorithm. Laravel encrypted value are signed using a message authentication code and value can not be modify once encrypted.

2. Configuration.

Before using laravel encrypter, you must set a key option in your config/app.php configuration file. You should use the php artisan key:generate
command to generate this key since this artisan command will use PHP’s secure random bytes generator to build your key. If this value is not properly set, all values encrypted by Laravel will be insecure.

3. Using The Encrypter.

Encrypting A Value

We can encrypt a value using the encrypt helper. All encrypted value are encrypted using open source implementation and the AES-256-CBC cipher. All encrypted values are signed with a message authentication code (MAC) to detect any modifications to the encrypted string

Let’s look at a simple example.

<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    
    public function storeSecret(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $user->fill([
            'secret' => encrypt($request->secret)
        ])->save();
    }
}

Encrypting Without Serialization

Encrypted values are passed through serialize during encryption which is allows for encryption of object and arrays. Non-PHP client recieving encrypted values will need to unserialize the data. If you want to encrypt and decrypt values without serialization,
you can use the encryptString and decryptString method.

use Illuminate\Support\Facades\Crypt;

$encrypted = Crypt::encryptString('Hello world.');

$decrypted = Crypt::decryptString($encrypted);

Decrypting A Value

You may decrypt values using the decrypt helper. If the value can not be properly decrypted, such as when the MAC is invalid, an Illuminate/Contracts/Encryption/DecryptException will be thrown.

use Illuminate\Contracts\Encryption\DecryptException;

try {
    $decrypted = decrypt($encryptedValue);
} catch (DecryptException $e) {
    //
}

Advertisements

Add Comment

📖 Read More