web-dev-qa-db-fra.com

Crypter / décrypter les champs de base de données dans laravel

Je crypte/décrypte les valeurs du champ DB dans Laravel via des accesseurs et des mutateurs, ce qui fonctionne bien dans les transactions éloquentes normales.

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');
    }
}

Mais le chiffrement et le déchiffrement ne fonctionnent pas dans les conditions suivantes

  1. Des relations éloquentes
  2. Requêtes brutes DB

Travail

$person = Person::find($person_id);
$person->firstName;

Ca ne fonctionne pas

$user = User::find($user_id);
$user->person->firstName;
8
Kalyana Kannan

Vous auriez probablement le chiffrement au niveau de la base de données, comme si quelqu'un avait accès à la base de données, vous ne vouliez pas qu'il puisse lire les données médicales des gens en texte brut.

Vous pouvez créer un trait qui chiffre et déchiffre les données lors de l'enregistrement et de la récupération respectivement:

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;
    }
}

Vous pouvez ensuite simplement appliquer le trait à vos modèles et définir une propriété appelée $ cryptable qui est un tableau de colonnes dont les données doivent être cryptées:

class YourModelextends Model
{
    use Encryptable;

    protected $encryptable = [
        'code',
        'keys',
        'allergies'
    ];
}
9
iman

Vous pouvez le faire avec les façades de Laravel Crypt . veuillez suivre cet exemple.

use Illuminate\Support\Facades\Crypt;

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

$decrypted = Crypt::decryptString($encrypted);

J'ai implémenté à partir de ce lien d'article: https://hackthestuff.com/article/laravel6-encryption-and-decryption-model-data-using-crypt-class

2
Harsukh Makwana

Sur la base d'Iman, sa réponse a changé le trait afin qu'il fonctionne avec le tableau de lancers de Laravel self.

<?php
namespace App\Library\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 (isset($this->casts[$key]) && $value !== '' && !is_null($value) && $this->casts[$key] == 'encrypt') {
            $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 (isset($this->casts[$key]) && $value !== '' && !is_null($value) && $this->casts[$key] == 'encrypt') {
            $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->casts as $key => $value) {
            if($value == 'encrypt') {
                if (isset($attributes[$key]) && $attributes[$key] !== '' && !is_null($attributes[$key])) {
                    $attributes[$key] = decrypt($attributes[$key]);
                }
            }
        }
        return $attributes;
    }
}
2
Lennart