magros/laravel-model-encryption

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

dev-master 2021-01-30 21:22 UTC

This package is auto-updated.

Last update: 2024-08-29 04:48:50 UTC


README

Scrutinizer Code Quality Downloads License Codeship Build Status Code Intelligence Status

laravel-model-encryption

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

如何安装

运行 composer 安装

    composer require magros/laravel-model-encryption

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

    'providers' => [
        ...
        \Magros\Encryptable\EncryptServiceProvider::class,
    ],

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

     php artisan vendor:publish --provider=Magros\Encryptable\EncryptServiceProvider

如何使用

  1. 您必须在 .env 文件中添加 ENCRYPT_KEYENCRYPT_PREFIX 或者在 config/encrypt.php 文件中设置它们

  2. 使用 Magros\Encryptable\Encryptable 特质

    use Magros\Encryptable\Encryptable;
  3. 在您的 Model 上设置 $encryptable 数组。

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

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

    如果您数据库中已有当前数据,可以使用命令 php artisan encryptable:encryptModel 'App\User' 加密它。

    另外,您可以使用命令 php artisan encryptable:decryptModel 'App\User' 解密。

    注意:您必须首先实现 Encryptable 特质并设置 $encryptable 属性。

  6. 如果您使用存在和唯一规则与加密值,请用 exists_encryptedunique_encrypted 替换。

    $validator = validator(['email'=>'foo@bar.com'], ['email'=>'exists_encrypted:users,email']);
  7. 您仍然可以使用 where 函数。

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

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