encrypt and decode


Usage

  • ##IntroductionLaravel’s encryption mechanism uses AES-256 and AES- provided by OpenSSL 128 encryption. It is strongly recommended that you use Laravel's built-in encryption tools instead of other encryption algorithms. All Laravel encrypted results are signed using a Message Authentication Code (MAC) so that the underlying value cannot be modified after encryption.

##SetupBefore using Laravel's encryption tools, you must first set up

config/app.
key
option in php

configuration file. You should generate the key using the

php artisan key:generate

command, an Artisan command that uses PHP's secure random byte generator to build the key. If the

key

value is not set correctly, all values ​​encrypted by Laravel will be unsafe.

UsageEncrypt a valueYou can use the auxiliary Function encrypt to encrypt a value. All encrypted values ​​are encrypted using OpenSSL's AES-256-CBC. Additionally, all encrypted values ​​are signed using a Message Authentication Code (MAC) to detect if the encrypted string has been tampered with:

<?php
   namespace App\Http\Controllers;
   use App\User;use Illuminate\Http\Request;
   use App\Http\Controllers\Controller;class UserController extends Controller{  
     /**
     * 存储用户的保密信息
     *
     * @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();  
        }
     }

No serialization encryption

During the encryption process, the encrypted value serialize is passed after serialization, allowing encrypted objects and arrays. Therefore, non-PHP clients receiving encrypted values ​​need to unserialize deserialize the data. If you want to encrypt and decrypt values ​​without serializing, you can use the encryptString and decryptString methods of the Crypt Facade:

use Illuminate\Support\Facades\Crypt;
$encrypted = Crypt::encryptString('Hello world.');
$decrypted = Crypt::decryptString($encrypted);

Decrypt a value

You can use the helper function decrypt to decrypt. If the value cannot be decrypted correctly, for example, if the MAC is invalid, an exception Illuminate\Contracts\Encryption\DecryptException will be thrown:

use Illuminate\Contracts\Encryption\DecryptException;try { 
   $decrypted = decrypt($encryptedValue);
  } 
catch (DecryptException $e) {
    //
}
This article was first published on LearnKu.com on the website.