How To Encrypt Api Request & Response In Laravel

How To Encrypt Api Request & Response In Laravel

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


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.


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


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


*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