adityadarma/laravel-database-cryptable

为Laravel的加密值数据库

2.0.1 2024-07-19 08:53 UTC

This package is auto-updated.

Last update: 2024-09-19 09:06:10 UTC


README

Laravel数据库加密,以确保数据安全。

Laravel安装说明

在终端中,从项目根目录运行

composer require adityadarma/laravel-database-cryptable

支持

  • MYSQL
  • MariaDB
  • PostgreSQL(需要pgcrypto扩展)

用法

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

例如

    
    use AdityaDarma\LaravelDatabaseCryptable\Traits\CryptableAttribute;

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

通过包含CryptableAttribute特性,Eloquent提供的setAttribute()getAttribute()getAttributeFromArray()方法被重写,以包含一个额外的步骤。

搜索加密字段示例

可以通过调用类似Laravel Eloquent的whereorWherewhereEncryptedorWhereEncrypted函数来搜索加密字段。可以通过调用orderByEncrypted来对加密数据进行排序,类似于Laravel Eloquent的orderBy

    namespace App\Http\Controllers;

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

加密现有数据

如果您数据库中已有数据,可以使用php artisan crypt:encrypt User命令对其进行加密。

此外,您还可以使用php artisan crypt:decrypt 'User命令对其进行解密。

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

存在和唯一验证规则

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

我能加密我的User模型的所有数据吗?

除了ID之外,您可以加密您想要的所有内容

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

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

致谢

本包受到了以下包的启发

许可

本包采用MIT许可。祝您享受!