Laravel 5.3 自定义加密服务实现详解
前言
本文将深入探讨在 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; $iprikey) === 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 文件,在 providers 和 aliases 数组中添加相应的服务提供者与别名映射。
'providers' => [
\App\Providers\MyCryptServiceProvider::class,
],
'aliases' => [
'MyCrypt' => \App\Facades\CryptFacades::class,
]
编写加密服务的配置文件
由于 CryptService 类依赖外部配置参数,因此需要额外创建 /config/crypt.php 配置文件。在实际项目应用中,可根据具体需求灵活调整配置文件结构及加密服务类的关联方式。
<?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 中的使用示例
第一步,使用 artisan 命令行工具生成 Controller 文件。
php artisan make:controller IndexController
第二步,编辑生成的 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
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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($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);
}
}
第三步,在 /routes/web.php 路由文件中添加对应的访问路由。
Route::get('/test', 'IndexController@test');
第四步,通过浏览器访问对应 URL 以验证加密解密结果是否符合预期。
总结
上述内容涵盖了本文的全部知识点,期望能为各位的学习或工作提供有益参考。若有任何疑问,欢迎留言交流,感谢大家对本站的支持。