How To Encrypt Api Request & Response In Laravel

How To Encrypt Api Request & Response In Laravel

Play this article

Sometimes we have sensitive and private data like a bank data , so this data must be encrypted and protected from the man in the middle attack .
in this article we will use AES Encryption Algorithm to encrypt api request and response , Do not worry tzsk/crypton package does it in simple and easy steps.
Let's go and see how to do it .

Step 1: install tzsk/crypton package .

composer require tzsk/crypton

Step 2: Publish config file

php artisan crypton:publish

Step 3: Add an environment variable in the .env file

CRYPTON_KEY=your-encryption-key

TIP: You can easily generate an encryption key by running php artisan key:generate then copy the generated key. Then again run: php artisan key:generate to make the key used by crypton and the default application key different.

Step 4: Usage

Start off by adding a Middleware in the app/Http/Kernel.php file.

$routeMiddleware = [
    'crypton' => \Tzsk\Crypton\Middleware\EncryptRequestResponse::class,
];

Step 5: Now, add this middleware to any api routes or groups.

example:

Route::middleware(['crypton'])->group(function () {

    Route::get('posts', function (Request $request) {

        $posts = Post::all();
        return $posts ;

    });

});

: here we get all posts and crypton middleware encrypt response automatic

Step 6: Now, Let's see and test it in postman.

first we will see normal response without encryption

image_2022-04-23_004939903.png

And now look to the a new form of response (encrypted)

after.PNG

*as you saw response has encrypted

note: all responses will returned in json form has one parameter called payload
so when you send data you must send it encrypted in payload parameter and middleware decrypt it immediately and merge it in request class