加密


1、配置

在使用Laravel的加密器之前,应该在配置文件config/app.php中设置key选项为32位随机字符串。如果这个值没有被设置,所有Laravel加密过的值都是不安全的。

2、基本使用

2.1 加密

你可以使用Crypt门面对数据进行加密,所有加密值都使用OpenSSL和AES-256-CBC密码进行加密。此外,所有加密值都通过一个消息认证码(MAC)来检测对加密字符串的任何修改。

例如,我们可以使用encrypt方法加密secret属性并将其存储到Eloquent模型:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Crypt;
  4. use App\User;
  5. use Illuminate\Http\Request;
  6. use App\Http\Controllers\Controller;
  7. class UserController extends Controller{
  8. /**
  9. * Store a secret message for the user.
  10. *
  11. * @param Request $request
  12. * @param int $id
  13. * @return Response
  14. */
  15. public function storeSecret(Request $request, $id)
  16. {
  17. $user = User::findOrFail($id);
  18. $user->fill([
  19. 'secret' => Crypt::encrypt($request->secret)
  20. ])->save();
  21. }
  22. }

2.2 解密

当然,你可以使用Crypt门面上的decrypt方法进行解密。如果该值不能被解密,例如MAC无效,将会抛出一个Illuminate\Contracts\Encryption\DecryptException异常:

  1. use Illuminate\Contracts\Encryption\DecryptException;
  2. try {
  3. $decrypted = Crypt::decrypt($encryptedValue);
  4. } catch (DecryptException $e) {
  5. //
  6. }