Laravel - Encryption

Laravel - Encryption

Encryption is the process of converting plain text into a message using some algorithm so that any third party cannot read the information. This is useful for transferring sensitive information, as there is less chance for an attacker to target the information being transferred.

Encryption is done using a process called Cryptography . The text to be encrypted is called plain text and the text or message received after encryption is called ciphertext . The process of converting ciphertext into plain text is called decryption .

Laravel uses AES-256 and AES-128 encryptor which uses Open SSL for encryption. All values ​​included in Laravel are signed using a protocol -based message authentication code, so the underlying value cannot be tampered with once it is encrypted.


The command used to generate key in Laravel is shown below −

php artisan key:generate

Note that this command uses the PHP Safe Random Byte Generator and you can see the output as shown in the screenshot below −

The above command helps in generating a key that can be used in a web application. Look at the screenshot below.

The note

The values ​​for encryption are properly aligned in the config/app.php file , which includes two options for encryption, namely key and cipher . If a value using this key is not properly aligned, all values ​​encrypted in Laravel will be insecure.

Encryption process

Value encryption can be done using the encryption helper in Laravel's class controllers. These values ​​are encrypted using OpenSSL and an AES-256 cipher. All encrypted values ​​are signed with a message authentication code (MAC) to verify any changes to the encrypted string.

The code shown below is referenced in the controller and is used to store a secret or confidential message.

<? php

namespace App \Http\Controllers ; 

use Illuminate \Http\Request ; use App \Http\Controllers\Controller ; 

class DemoController extends Controller { ** * Store a secret message for the user . * * @param Request $request
       * @param int $id
       * @return Response */   
   public function storeSecret ( Request $request , $id ) { 

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

Decryption process

Value decryption is done using the decryption helper . Observe the following lines of code −

use Illuminate \Contracts\Encryption\DecryptException ; 

// Exception for decryption thrown in facade try { 
   $decrypted = decrypt ( $encryptedValue ); } catch ( DecryptException $e ) { // }
   Note that if the decryption process was not successful due to the use of an invalid MAC address, an appropriate exception is thrown.