dongyi6183 2018-03-27 01:53
浏览 701
已采纳

Laravel 5中的加密和解密

I have been looking for ideas on encrypting and decrypting values in Laravel (like VIN Numbers, Employee ID Card Numbers, Social Security Numbers, etc.) and recently found this on the Laravel website: https://laravel.com/docs/5.6/encryption

My question is, how would I print the decrypted values on a blade template? I could see going through the controller and setting a variable and then printing it to a Blade, but I was curious as to how I would also print a decrypted value to an index? Like so...

@foreach($employees as $employee)
{{$employee->decrypted value somehow}}
{{$employee->name}}
@endforeach
  • 写回答

5条回答 默认 最新

  • dongyun4010 2018-03-27 15:20
    关注

    You can handle encrypted attributes with a trait (app/EncryptsAttributes.php):

    namespace App;
    
    trait EncryptsAttributes {
    
        public function attributesToArray() {
            $attributes = parent::attributesToArray();
            foreach($this->getEncrypts() as $key) {
                if(array_key_exists($key, $attributes)) {
                    $attributes[$key] = decrypt($attributes[$key]);
                }
            }
            return $attributes;
        }
    
        public function getAttributeValue($key) {
            if(in_array($key, $this->getEncrypts())) {
                return decrypt($this->attributes[$key]);
            }
            return parent::getAttributeValue($key);
        }
    
        public function setAttribute($key, $value) {
            if(in_array($key, $this->getEncrypts())) {
                $this->attributes[$key] = encrypt($value);
            } else {
                parent::setAttribute($key, $value);
            }
            return $this;
        }
    
        protected function getEncrypts() {
            return property_exists($this, 'encrypts') ? $this->encrypts : [];
        }
    
    }
    

    Use it in your models when necessary:

    class Employee extends Model {
    
        use EncryptsAttributes;
    
        protected $encrypts = ['cardNumber', 'ssn'];
    
    }
    

    Then you can get and set the attributes without thinking about the encryption:

    $employee->ssn = '123';
    {{ $employee->ssn }}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog