加密/解密laravel中的数据库字段

Kal*_*nan 6 php encryption laravel eloquent laravel-5

我正在通过访问器和更改器对Laravel中的DB字段值进行加密/解密,这在正常的雄辩事务中运行正常。

class Person extends Model
{
    use Notifiable;
    protected $table = 'person';

    public function getFirstNameAttribute($value)
    {
        return Crypt::decryptString($value);
    }
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = array();

    protected function user()
    {
        return $this->belongsTo('App\Models\User', 'useraccount_id', 'id');
    }
}
Run Code Online (Sandbox Code Playgroud)

但是加密和解密在以下情况下不起作用

  1. 雄辩的关系
  2. 数据库原始查询

工作中

$person = Person::find($person_id);
$person->firstName;
Run Code Online (Sandbox Code Playgroud)

无法运作

$user = User::find($user_id);
$user->person->firstName;
Run Code Online (Sandbox Code Playgroud)

ima*_*man 7

您可能会在数据库级别进行加密,就好像某人可以访问数据库一样,您不希望他们能够以纯文本格式读取人们的医疗数据。

您可以创建一个特征,分别在保存和检索时对数据进行加密和解密:

namespace App\Traits;

use Illuminate\Support\Facades\Crypt;
trait Encryptable
{
    /**
     * If the attribute is in the encryptable array
     * then decrypt it.
     *
     * @param  $key
     *
     * @return $value
     */
    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);
        if (in_array($key, $this->encryptable) && $value !== '') {
            $value = decrypt($value);
        }
        return $value;
    }
    /**
     * If the attribute is in the encryptable array
     * then encrypt it.
     *
     * @param $key
     * @param $value
     */
    public function setAttribute($key, $value)
    {
        if (in_array($key, $this->encryptable)) {
            $value = encrypt($value);
        }
        return parent::setAttribute($key, $value);
    }
    /**
     * When need to make sure that we iterate through
     * all the keys.
     *
     * @return array
     */
    public function attributesToArray()
    {
        $attributes = parent::attributesToArray();
        foreach ($this->encryptable as $key) {
            if (isset($attributes[$key])) {
                $attributes[$key] = decrypt($attributes[$key]);
            }
        }
        return $attributes;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以将特征应用于模型,并定义一个名为$ encryptable的属性,该属性是应加密其数据的列的数组:

class YourModelextends Model
{
    use Encryptable;

    protected $encryptable = [
        'code',
        'keys',
        'allergies'
    ];
}
Run Code Online (Sandbox Code Playgroud)

  • 在复制和粘贴时应称赞原始作者会很体面。https://laracasts.com/discuss/channels/laravel/encrypting-model-data (4认同)

Har*_*ana 6

你可以使用 laravel 的Crypt Facades 来做到这一点。请按照这个例子。

use Illuminate\Support\Facades\Crypt;

$encrypted = Crypt::encryptString('Hello world.');

$decrypted = Crypt::decryptString($encrypted);
Run Code Online (Sandbox Code Playgroud)

我从这篇文章链接实现:https://hackthestuff.com/article/laravel6-encryption-and-decryption-model-data-using-crypt-class