crudly / encrypted
为 Eloquent 设计的加密和散列类
1.6.0
2024-07-12 07:07 UTC
Requires
- laravel/framework: ^9.0|^10.0|^11.0
Requires (Dev)
- orchestra/testbench: ^7.0|^8.0
- phpunit/phpunit: ^9.0|^10.0
This package is auto-updated.
Last update: 2024-09-12 07:30:18 UTC
README
注意 由于哈希现在是原生类型之一,并且加密已经存在一段时间了,因此此包对于新项目不再需要。我们可能会继续更新它几年,因为这通常只需要更新版本标签。
Laravel Eloquent 的自定义类型转换类,用于加密或散列您的值。该包体积小,只提供了一些简单、经过良好测试的功能。
protected $casts = [ // hashes the value when assigning to $model->password 'password' => Password::class, // encrypts on write, decrypts on read 'classified' => Encrypted::class, // encrypts on write, decrypts & typecasts on read 'secret' => Encrypted::class.':integer', ];
安装
使用 composer。
$ composer require crudly/encrypted
使用
将模型中的任何列标记为加密。
<?php namespace App; use Crudly\Encrypted\Encrypted; use Illuminate\Database\Eloquent\Model; class MyModel extends Model { protected $casts = [ 'something_secret' => Encrypted::class, ]; }
您可以像平时一样处理属性,但它将在数据库中加密。
$mm = new MyModel; $mm->someting_secret = 'classified_info'; $mm->save();
类型转换
加密序列化变量,解密反序列化,因此您得到的就是您放入的。这通常意味着不需要类型转换。
但有时您希望将所有内容转换为某种类型,即使您放入了其他内容。在这些情况下,您可以指定类型(支持所有 Eloquent 默认类型转换)
<?php namespace App; use Crudly\Encrypted\Encrypted; use Illuminate\Database\Eloquent\Model; class MyModel extends Model { protected $casts = [ 'encrypted_column' => Encrypted::class, 'an_integer' => Encrypted::class.':integer', 'a_string' => Encrypted::class.':string', 'decimal_with_two_places' => Encrypted::class.':decimal:2', ]; }
密码散列
这也可以用于在写入时散列密码。
<?php namespace App; use Crudly\Encrypted\Password; use Illuminate\Database\Eloquent\Model; class MyUser extends Model { protected $casts = [ 'password' => Password::class, ]; }
使用 bcrypt
散列密码。您可以使用 Hash
门面来检查字符串与散列密码是否匹配。
$mu = new MyUser; $mu->password = 'secret'; $mu->password; // returns a hash Hash::check('secret', $mu->password); //returns true Hash::check('hunter2', $mu->password); //returns false
待办事项
可能添加通过选项自定义密钥和加密方式,例如 Encrypted::class.':string,AckfSECXIvnK5r28GVIWUAxmbBSjTsmF'
和 Encrypted::class.':string,AckfSECXIvnK5r28GVIWUAxmbBSjTsmF,AES-128-CBC'
。以及密码散列选项。