waseem/laravel-data-encryption

使用Eloquent模型的getAttribute和setAttribute方法自动加密和解密数据。

1.0.1 2023-06-25 18:23 UTC

This package is auto-updated.

Last update: 2024-09-25 21:18:18 UTC


README

一个用于在Laravel中加密数据模型的特质,它自动加密和解密模型数据,覆盖了Eloquent模型的getAttribute和setAttribute方法。

如何安装

运行composer安装

    composer require waseem/laravel-data-encryption

将ServiceProvider添加到app/config.php文件中

    'providers' => [
        ...
        \Waseem\Encipher\EncipherServiceProvider::class,
    ],

发布配置文件,这将创建config/encrypt.php

     php artisan vendor:publish --provider=Waseem\Encipher\EncipherServiceProvider

如何使用

  1. 您必须在.env文件中添加SECRET_ENCRYPT_KEYENCRYPT_PREFIX或将其设置在config/encrypt.php文件中

  2. 使用Waseem\Encipher\Encipher特质

    use Waseem\Encipher\Encipher;
  3. 在您的Model上设置$encipher数组。

    protected $encipher = ['encrypted_property'];
  4. 这里是一个完整的示例

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use Waseem\Encipher\Encipher;
    
    class User extends Model
    {
    
        use Encipher;
    
        /**
         * The attributes that should be encrypted when stored.
         *
         * @var array
         */
        protected $encipher = [ 'email', 'name' , 'mobile'];
     
        /**
        * Optionally you can define the attributes that should be converted to camelcase when retrieve.
        *
        * @var array
        */
         protected $camelcase = ['name'];
    }
  5. 可选。加密当前数据

    如果您的Laravel应用程序版本为5.8+

    如果您数据库中有当前数据,可以使用php artisan encipher:encryptionModel 'App\Models\User'命令进行加密。

    此外,您可以使用php artisan encipher:decryptionModel 'App\Models\User'命令进行解密。

    注意:您必须首先实现Encipher特质并设置$encipher属性

  6. 如果您使用存在和唯一规则与加密值,请将其替换为exists_encrypted和unique_encrypted

    $validator = validator(['email'=>'wasi@demo.com'], ['email'=>'exists_encrypted:users,email']);

    或者

    $rules=array(
        'email' => 'required|unique_encrypted:users,email'
    );
    $messages=array(
        "email.unique_encrypted"=>"The email has already been taken."
    );
  7. 您仍然可以使用where函数

    $validator = User::where('email','wasi@demo.com')->first();

    自动将wasi@demo.com加密并传递给查询构建器。