laravel 5.3中自定义加密服务的方案详解


Posted in PHP onMay 09, 2017

前言

本文介绍的是laravel 5.3中自定义加密服务的方案,利用laravel的服务容器,实现自定义加密服务注册(示例是支持长字符串的RSA加密),下面来看看详细的介绍:

创建加密解密服务类

文件地址 /app/Service/Common/CryptService.php 代码如下

下面这个是个人写的支持长字符串的RSA加密类作为示例,自定义加密的话只需更改这个文件的代码就好,其它操作只是为了实现依赖注入。

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

 public function select($select = 'rsa_api')
 {
  $config = config('crypt');
  if (array_key_exists($select, $config)) {
   $this->config = $config[$select];
   $this->private_key_size = $this->config['openssl_config']['private_key_bits'];
  } else {
   return false;
  }
  $this->keypath = dirname(dirname(dirname(__DIR__))) . $this->config['path'];
  if(!file_exists($this->keypath)){
   mkdir($this->keypath,"0777",true);
  }
  $this->prikey_path = $this->keypath . $this->config['private_key_file_name'];
  $this->pubkey_path = $this->keypath . $this->config['public_key_file_name'];
  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['openssl_config']);
  openssl_pkey_export($res, $this->prikey);
  file_put_contents($this->prikey_path, $this->prikey);
  $pubkey = openssl_pkey_get_details($res);
  $this->pubkey = $pubkey['key'];
  file_put_contents($this->pubkey_path, $this->pubkey);
  return $test = ['prikey' => $this->prikey, 'pubkey' => $this->pubkey];
 }

 public function encryptPrivate($data){
  $crypt = $this->encrypt_split($data);
  $crypted = '';
  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 = '';
  foreach ($crypt as $k=>$c){
   if($k!=0) $crypted.="@";
   $crypted.=base64_encode($this->doEncryptPublic($c));
  }
  return $crypted;
 }

 public function decryptPublic($data){
  $decrypt = explode('@',$data);
  $decrypted = "";
  foreach ($decrypt as $k=>$d){
   $decrypted .= $this->doDecryptPublic(base64_decode($d));
  }
  return $decrypted;
 }
 public function decryptPrivate($data){
  $decrypt = explode('@',$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 = '';
  if (@openssl_private_encrypt($data, $rs, $this->prikey) === FALSE) {
   return NULL;
  }
  return $rs;
 }

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

创建门面facades

文件地址 /app/Facades/CryptFacades.php 代码如下:

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

class CryptFacades extends Facade{
 public static function getFacadeAccessor()
 {
  return 'MyCrypt';
 }
}

注册服务

创建文件 /app/Providers/MyCryptServiceProvider.php 代码如下:

其实也可以在AppServiceProvider中注册,就不用另外建个MyCryptServiceProvider.php文件了

而且在/config/app.php中一般也已经有了AppServiceProvider的声明

<?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('MyCrypt',CryptService::class);
 }
}

在配置中声明

文件地址 /config/app.php 在providershe和aliases中添加

'providers' => [
 \App\Providers\MyCryptServiceProvider::class,
],

'aliases' => [
 'MyCrypt' => \App\Facades\CryptFacades::class,
]

编写自定义加密解密服务的配置文件

/config/crypt.php 因为我写的CryptService有用到配置文件,所以需要再添加个配置文件。在实际项目中,可以根据需要自行设置配置文件和加密服务类。

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

在Controller中使用的示例

1、artisan创建Controller文件

php artisan make:controller IndexController

2、编辑IndexController

<?php
namespace App\Http\Controllers;

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

 public function test(){
  $crypt = MyCrypt::select('rsa_api');
  $crypt->makeKey();
  $short = "abcd";
  $long = "
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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aa";

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

  $req['long'] = $long;
  $req['long_private_encrypt'] = $crypt->encryptPrivate($long);
  $req['long_public_decrypt'] = $crypt->decryptPublic($req['long_private_encrypt']);
  dump($req);
  //dd($req);
 }
}

3、在/routes/web.php添加路由

Route::get('/test', 'IndexController@test');

4、浏览器访问验证结果

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

PHP 相关文章推荐
手把手教你使用DedeCms的采集的图文教程
Mar 11 PHP
php中ob(Output Buffer 输出缓冲)函数使用方法
Jul 21 PHP
PHP下一个非常全面获取图象信息的函数
Nov 20 PHP
php读取xml实例代码
Jan 28 PHP
8个出色的WordPress SEO插件收集
Feb 26 PHP
php实现自动获取生成文章主题关键词功能的深入分析
Jun 03 PHP
Thinkphp模板中截取字符串函数简介
Jun 17 PHP
destoon在360浏览器下出现用户被强行注销的解决方法
Jun 26 PHP
php开发时容易忘记的一些技术细节
Feb 03 PHP
JavaScript实现删除电脑的关机键
Jul 26 PHP
php微信公众平台开发(四)回复功能开发
Dec 06 PHP
Yii框架 session 数据库存储操作方法示例
Nov 18 PHP
Win7环境下Apache连接MySQL提示连接已重置的解决办法
May 09 #PHP
ThinkPHP使用getlist方法实现数据搜索功能示例
May 08 #PHP
ThinkPHP实现图片上传操作的方法详解
May 08 #PHP
PHP开发中csrf攻击的简单演示和防范
May 07 #PHP
ThinkPHP框架实现数据增删改
May 07 #PHP
thinkphp 验证码 的使用小结
May 07 #PHP
解析 thinkphp 框架中的部分方法
May 07 #PHP
You might like
PHP实现时间轴函数代码
2011/10/08 PHP
PHP之图片上传类实例代码(加了缩略图)
2016/06/30 PHP
Laravel学习教程之从入口到输出过程详解
2017/08/27 PHP
PHP tp5中使用原生sql查询代码实例
2020/10/28 PHP
通过修改referer下载文件的方法
2008/05/11 Javascript
JavaScript高级程序设计 阅读笔记(二十一) JavaScript中的XML
2012/09/14 Javascript
js给onclick事件赋值,动态传参数实例解说
2013/03/28 Javascript
ajax请求get与post的区别总结
2013/11/04 Javascript
jQuery打印图片pdf、txt示例代码
2014/07/22 Javascript
JavaScript sup方法入门实例(把字符串显示为上标)
2014/10/20 Javascript
基于Flowplayer打造一款免费的WEB视频播放器附源码
2015/09/06 Javascript
JS实现显示带倒影的图片横排居中放大展示特效实例【测试可用】
2016/08/23 Javascript
Bootstrap标签页(Tab)插件使用方法
2017/03/21 Javascript
vue-cli之router基本使用方法详解
2017/10/17 Javascript
layui自定义ajax左侧三级菜单
2019/07/26 Javascript
vue+elementui 对话框取消 表单验证重置示例
2019/10/29 Javascript
vue2.0实现列表数据增加和删除
2020/06/17 Javascript
vue实现多个echarts根据屏幕大小变化而变化实例
2020/07/19 Javascript
结合axios对项目中的api请求进行封装操作
2020/09/21 Javascript
Vue router传递参数并解决刷新页面参数丢失问题
2020/12/02 Vue.js
python在多玩图片上下载妹子图的实现代码
2013/08/13 Python
简单掌握Python中glob模块查找文件路径的用法
2016/07/05 Python
python正则实现提取电话功能
2018/02/24 Python
如何优雅地改进Django中的模板碎片缓存详解
2018/07/04 Python
Python使用Flask-SQLAlchemy连接数据库操作示例
2018/08/31 Python
python2 与 pyhton3的输入语句写法小结
2018/09/10 Python
python SocketServer源码深入解读
2019/09/17 Python
Django ORM filter() 的运用详解
2020/05/14 Python
移动端Html5中百度地图的点击事件
2019/01/31 HTML / CSS
高街生活方式全球在线商店:AZBRO
2017/08/26 全球购物
如果有两个类A,B,怎么样才能使A在发生一个事件的时候通知B
2016/03/12 面试题
小学家长会邀请函
2014/01/23 职场文书
社会工作专业求职信
2014/07/15 职场文书
员工工作自我评价
2014/09/26 职场文书
文明班级申报材料
2014/12/24 职场文书
初中思想品德教学反思
2016/02/24 职场文书