quevlu/laravel-database-encryption

通过Eloquent自动加密和解密数据库

1.1.0 2021-08-30 01:21 UTC

This package is auto-updated.

Last update: 2024-09-24 07:37:24 UTC


README

Latest Version on Packagist MIT Licensed Build Status Total Downloads

使用openssl加密和解密Laravel模型属性的包

主要特性

  • 轻松加密和解密数据库字段
  • 最小化配置
  • 使用以下方式包含搜索加密数据:`whereEncrypted` 和 `orWhereEncrypted`
  • 使用openssl加密和解密字段

要求

  • Laravel: >= 5
  • PHP: >= 7.3

模式要求

加密值通常比纯文本值长,有时长得多。您可能会发现数据库表中列的宽度需要更改以存储此包生成的加密值。

我们强烈建议将列类型更改为 TEXTLONGTEXT

安装

步骤1:Composer

通过Composer命令行

$ composer require elgibor-solution/laravel-database-encryption

步骤2:将ServiceProvider添加到您的app/config.php文件(Laravel 5.4或以下)

将服务提供者添加到config/app.php配置文件中的providers数组中,如下所示

    'providers' => [
        ...
        \ESolution\DBEncryption\Providers\DBEncryptionServiceProvider::class,
    ],

用法

使用任何希望应用加密的Eloquent模型中的EncryptedAttribute特性,并定义一个包含要加密的属性列表的protected $encrypted数组。

例如

    
    use ESolution\DBEncryption\Traits\EncryptedAttribute;

    class User extends Eloquent {
        use EncryptedAttribute;
       
        /**
         * The attributes that should be encrypted on save.
         *
         * @var array
         */
        protected $encryptable = [
            'first_name', 'last_name'
        ];
    }

通过包含EncryptedAttribute特性,Eloquent提供的setAttribute()getAttribute()getAttributeFromArray()方法被覆盖以包含额外的步骤。

搜索加密字段示例

可以通过调用与laravel eloquent中的whereorWhere类似的whereEncryptedorWhereEncrypted函数来搜索加密字段。

    namespace App\Http\Controllers;

    use App\User;
    class UsersController extends Controller {
        public function index(Request $request)
        {
            $user = User::whereEncrypted('first_name','john')
                        ->orWhereEncrypted('last_name','!=','Doe')->firstOrFail();
            
            return $user;
        }
    }

加密当前数据

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

此外,您还可以使用:php artisan encryptable:decryptModel 'App/User' 命令进行解密。

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

存在性和唯一性验证规则

如果您使用存在性和唯一性规则与加密值,请将其替换为`exists_encrypted`和`unique_encrypted` php $validator = validator(['email'=>'foo@bar.com'], ['email'=>'exists_encrypted:users,email']); $validator = validator(['email'=>'foo@bar.com'], ['email'=>'unique_encrypted:users,email']);

常见问题解答

我可以搜索加密数据吗?

是的!您将能够搜索由本包加密的属性。如果您需要搜索数据,请使用whereEncryptedorWhereEncrypted函数

    User::whereEncrypted('email','test@gmail.com')->orWhereEncrypted('email','test2@gmail.com')->firstOrFail();

当模型使用EncryptedAttribute时,它将自动添加到Eloquent中

我可以加密所有User模型数据吗?

除了ID之外,您可以加密您想要的一切

例如:在加密的电子邮件上登录

$user = User::whereEncrypted('email','test@gmail.com')->filter(function ($item) use ($request) {
        return Hash::check($password, $item->password);
    })->where('active',1)->first();

致谢

此包受以下项目的启发:austinheap/laravel-database-encryption magros/laravel-model-encryption DustApplication/laravel-database-model-encryption

许可

MIT许可(MIT)。请参阅许可文件以获取更多信息。