Home Backend Development PHP Tutorial Explain how to customize encryption services in laravel

Explain how to customize encryption services in laravel

Jan 02, 2018 pm 05:08 PM
laravel encryption customize

How to customize encryption service in laravel? This article mainly introduces you to the relevant information about customizing encryption services in laravel 5.3. The introduction in the article is very detailed and has certain reference learning value for everyone to learn or use laravel 5.3. Friends who need it can take a look below. I hope to be helpful.

Preface

This article introduces the solution of custom encryption service in laravel 5.3, using laravel's service container to implement custom encryption service Registration (the example is RSA encryption that supports long strings), let’s take a look at the detailed introduction:

Create encryption and decryption service class

File address/app/Service/Common/CryptService.php The code is as follows

The following is an RSA encryption class written by a person to support long strings as an example. If you want to customize encryption, you only need to change it. The code in this file is just fine, other operations are just for dependency injection.

<?php
namespace App\Service\Common;
class CryptService
{
 public $config,$keypath, $prikey_path, $pubkey_path, $prikey, $pubkey , $private_key_size;

 public function select($select = &#39;rsa_api&#39;)
 {
  $config = config(&#39;crypt&#39;);
  if (array_key_exists($select, $config)) {
   $this->config = $config[$select];
   $this->private_key_size = $this->config[&#39;openssl_config&#39;][&#39;private_key_bits&#39;];
  } else {
   return false;
  }
  $this->keypath = dirname(dirname(dirname(__DIR__))) . $this->config[&#39;path&#39;];
  if(!file_exists($this->keypath)){
   mkdir($this->keypath,"0777",true);
  }
  $this->prikey_path = $this->keypath . $this->config[&#39;private_key_file_name&#39;];
  $this->pubkey_path = $this->keypath . $this->config[&#39;public_key_file_name&#39;];
  if (file_exists($this->prikey_path))
   $this->prikey = file_get_contents($this->prikey_path);
  if (file_exists($this->pubkey_path))
   $this->pubkey = file_get_contents($this->pubkey_path);
  return $this;
 }

 public function makeKey()
 {
  $res = openssl_pkey_new($this->config[&#39;openssl_config&#39;]);
  openssl_pkey_export($res, $this->prikey);
  file_put_contents($this->prikey_path, $this->prikey);
  $pubkey = openssl_pkey_get_details($res);
  $this->pubkey = $pubkey[&#39;key&#39;];
  file_put_contents($this->pubkey_path, $this->pubkey);
  return $test = [&#39;prikey&#39; => $this->prikey, &#39;pubkey&#39; => $this->pubkey];
 }

 public function encryptPrivate($data){
  $crypt = $this->encrypt_split($data);
  $crypted = &#39;&#39;;
  foreach ($crypt as $k=>$c){
   if($k!=0) $crypted.="@";
   $crypted.=base64_encode($this->doEncryptPrivate($c));
  }
  return $crypted;
 }
 public function encryptPublic($data){
  $crypt = $this->encrypt_split($data);
  $crypted = &#39;&#39;;
  foreach ($crypt as $k=>$c){
   if($k!=0) $crypted.="@";
   $crypted.=base64_encode($this->doEncryptPublic($c));
  }
  return $crypted;
 }

 public function decryptPublic($data){
  $decrypt = explode(&#39;@&#39;,$data);
  $decrypted = "";
  foreach ($decrypt as $k=>$d){
   $decrypted .= $this->doDecryptPublic(base64_decode($d));
  }
  return $decrypted;
 }
 public function decryptPrivate($data){
  $decrypt = explode(&#39;@&#39;,$data);
  $decrypted = "";
  foreach ($decrypt as $k=>$d){
   $decrypted .= $this->doDecryptPrivate(base64_decode($d));
  }
  return $decrypted;
 }
 private function encrypt_split($data){
  $crypt=[];$index=0;
  for($i=0; $i<strlen($data); $i+=117){
   $src = substr($data, $i, 117);
   $crypt[$index] = $src;
   $index++;
  }
  return $crypt;
 }
 private function doEncryptPrivate($data)
 {
  $rs = &#39;&#39;;
  if (@openssl_private_encrypt($data, $rs, $this->prikey) === FALSE) {
   return NULL;
  }
  return $rs;
 }

 private function doDecryptPrivate($data)
 {
  $rs = &#39;&#39;;
  if (@openssl_private_decrypt($data, $rs, $this->prikey) === FALSE) {
   return null;
  }
  return $rs;
 }
 private function doEncryptPublic($data){
  $rs = &#39;&#39;;
  if (@openssl_public_encrypt($data, $rs, $this->pubkey) === FALSE) {
   return NULL;
  }
  return $rs;
 }
 private function doDecryptPublic($data)
 {
  $rs = &#39;&#39;;
  if (@openssl_public_decrypt($data, $rs, $this->pubkey) === FALSE) {
   return null;
  }
  return $rs;
 }
}
Copy after login

Create facade facades

##File address/app/Facades/CryptFacades.php The code is as follows:

<?php
namespace App\Facades;
use \Illuminate\Support\Facades\Facade;

class CryptFacades extends Facade{
 public static function getFacadeAccessor()
 {
  return &#39;MyCrypt&#39;;
 }
}
Copy after login

Registration Service

Create the file /app/Providers/MyCryptServiceProvider.php The code is as follows:


In fact, it can also be By registering in AppServiceProvider, there is no need to create another MyCryptServiceProvider.php file


And there is usually an AppServiceProvider declaration in /config/app.php

<?php
namespace App\Providers;

use App\Service\Common\CryptService;
use Illuminate\Support\ServiceProvider;

class MyCryptServiceProvider extends ServiceProvider
{
 /**
  * Bootstrap the application services.
  *
  * @return void
  */
 public function boot()
 {
  //
 }

 /**
  * Register the application services.
  *
  * @return void
  */
 public function register()
 {
  \App::bind(&#39;MyCrypt&#39;,CryptService::class);
 }
}
Copy after login

State in the configuration

File address/config/app.php Add

&#39;providers&#39; => [
 \App\Providers\MyCryptServiceProvider::class,
],

&#39;aliases&#39; => [
 &#39;MyCrypt&#39; => \App\Facades\CryptFacades::class,
]
Copy after login

to providershe and aliases to write Custom encryption and decryption service configuration file

/config/crypt.php Because the CryptService I wrote uses a configuration file, I need to add another configuration file. In actual projects, you can set up configuration files and encryption service classes as needed.

<?php
//基于laravel根目录,分隔符最好是用 DIRECTORY_SEPARATOR 常量代替
return [
 &#39;rsa_api&#39; => [
  &#39;path&#39;=>DIRECTORY_SEPARATOR.&#39;storage&#39;.DIRECTORY_SEPARATOR.&#39;rsakey&#39;.DIRECTORY_SEPARATOR,
  &#39;private_key_file_name&#39;=>&#39;private_key.pem&#39;,
  &#39;public_key_file_name&#39; =>&#39;public_key.pem&#39;,
  &#39;openssl_config&#39;=>[
   "digest_alg" => "sha512",
   "private_key_bits" => 1024,
   "private_key_type" => OPENSSL_KEYTYPE_RSA,
  ]
 ],
 &#39;rsa_data&#39;=>[
  &#39;path&#39;=>DIRECTORY_SEPARATOR.&#39;storage&#39;.DIRECTORY_SEPARATOR.&#39;rsakey&#39;.DIRECTORY_SEPARATOR,
  &#39;private_key_file_name&#39;=>&#39;private.pem&#39;,
  &#39;public_key_file_name&#39; =>&#39;public.pem&#39;,
  &#39;openssl_config&#39;=>[
   "digest_alg" => "sha512",
   "private_key_bits" => 1024,
   "private_key_type" => OPENSSL_KEYTYPE_RSA,
  ]
 ]
];
Copy after login

Example used in Controller

1. Artisan creates Controller file

php artisan make:controller IndexController
Copy after login

2. Edit IndexController

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use MyCrypt;
class IndexController extends Controller{

 public function test(){
  $crypt = MyCrypt::select(&#39;rsa_api&#39;);
  $crypt->makeKey();
  $short = "abcd";
  $long = "
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

  $req[&#39;short&#39;] = $short;
  $req[&#39;short_private_encrypt&#39;] = $crypt->encryptPrivate($short);
  $req[&#39;short_public_decrypt&#39;] = $crypt->decryptPublic($req[&#39;short_private_encrypt&#39;]);

  $req[&#39;long&#39;] = $long;
  $req[&#39;long_private_encrypt&#39;] = $crypt->encryptPrivate($long);
  $req[&#39;long_public_decrypt&#39;] = $crypt->decryptPublic($req[&#39;long_private_encrypt&#39;]);
  dump($req);
  //dd($req);
 }
}
Copy after login

3. Add routing in /routes/web.php

Route::get(&#39;/test&#39;, &#39;IndexController@test&#39;);
Copy after login

4. Browse Server access verification results

Related recommendations:

Explore how Laravel’s middleware is implemented

Writing APP interface (API) in laravel

Some practical tips to improve the performance of Laravel 5

The above is the detailed content of Explain how to customize encryption services in laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to effectively check the validity of Redis connections in Laravel6 project? How to effectively check the validity of Redis connections in Laravel6 project? Apr 01, 2025 pm 02:00 PM

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Apr 01, 2025 pm 12:21 PM

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

See all articles