sagalbot/encryptable

允许您在数据库中加密存储 Eloquent 属性,并在访问时自动解密。

v1.0.1 2020-05-03 19:00 UTC

This package is auto-updated.

Last update: 2024-09-15 01:03:02 UTC


README

一个 Laravel 5 扩展包,允许您在数据库中加密存储 Eloquent 模型属性,并在需要访问时自动解密。

example

安装

composer require sagalbot/encryptable

用法

此包实际上只是一个简单的特质和属性,您可以将其添加到您的 Eloquent 模型中。用法很简单

  1. 在使用 Laravel 的加密器之前,您必须在 config/app.php 配置文件中设置一个密钥选项。

    artisan key:generate

    注意: 如果您已经将 APP_KEY 设置在 .env 文件中,则应跳过此步骤。

  2. 使用 Sagalbot\Encryptable\Encryptable 特质

    use \Sagalbot\Encryptable\Encryptable;
  3. 在您的模型上设置 $encryptable 数组。

    protected $encryptable = ['my_encrypted_property'];
  4. 就这样!以下是一个完整的示例

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use Sagalbot\Encryptable\Encryptable;
    
    class MyEncryptedModel extends Model
    {
    
        use Encryptable;
    
        /**
         * The attributes that should be encrypted when stored.
         *
         * @var array
         */
        protected $encryptable = [ 'my_encrypted_property', 'another_secret' ];
    }

加密选项

默认情况下,该包使用全局的 encrypt()decrypt() Laravel 函数,它们只是指向容器中解析 Illuminate\Encryption\Encrypter::class 的别名。Laravel 的加密器使用 OpenSSL 提供的 AES-256 和 AES-128 加密,您可以在 Laravel 文档 中了解更多信息。

如果您需要调整特定模型加密和解密属性的方式,您可以在模型中覆盖 decryptAttributeencryptAttribute 方法

/**
 * @param $value
 */
protected function encryptAttribute($value)
{
    //  encrypt the value
}


/**
 * @param $value
 */
protected function decryptAttribute($value)
{
    //  decrypt the value
}

保密,安全

Keep it Secret, Keep it Safe

不要丢失您的加密密钥 - 没有它您无法解密存储的数据。