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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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...

Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Mar 31, 2025 pm 11:24 PM

Laravel schedule task run unresponsive troubleshooting When using Laravel's schedule task scheduling, many developers will encounter this problem: schedule:run...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

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,...

Which of the top ten virtual currency trading apps is the best? Which of the top ten virtual currency trading apps is the most reliable Which of the top ten virtual currency trading apps is the best? Which of the top ten virtual currency trading apps is the most reliable Mar 19, 2025 pm 05:00 PM

Top 10 virtual currency trading apps rankings: 1. OKX, 2. Binance, 3. Gate.io, 4. Kraken, 5. Huobi, 6. Coinbase, 7. KuCoin, 8. Crypto.com, 9. Bitfinex, 10. Gemini. Security, liquidity, handling fees, currency selection, user interface and customer support should be considered when choosing a platform.

Which is better, Django or Laravel? Which is better, Django or Laravel? Mar 28, 2025 am 10:41 AM

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

See all articles