[TOC]
### **1、配置**
在使用[Laravel](http://laravelacademy.org/tags/laravel "View all posts in Laravel")的[加密](http://laravelacademy.org/tags/%e5%8a%a0%e5%af%86 "View all posts in 加密")器之前,应该在配置文件`config/app.php`中设置`key`选项为32位随机字符串。如果这个值没有被设置,所有Laravel加密过的值都是不[安全](http://laravelacademy.org/tags/%e5%ae%89%e5%85%a8 "View all posts in 安全")的。
### **2、基本使用**
#### **2.1 加密**
你可以使用`[Crypt](http://laravelacademy.org/tags/crypt "View all posts in Crypt")`门面对数据进行加密,所有加密值都使用[OpenSSL](http://laravelacademy.org/tags/openssl "View all posts in OpenSSL")和`AES-256-CBC`密码进行加密。此外,所有加密值都通过一个消息认证码(MAC)来检测对加密字符串的任何修改。
例如,我们可以使用`encrypt`方法加密`secret`属性并将其存储到[Eloquent模型](http://laravelacademy.org/post/2995.html):
~~~
<?php
namespace App\Http\Controllers;
use Crypt;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserController extends Controller{
/**
* Store a secret message for the user.
*
* @param Request $request
* @param int $id
* @return Response
*/
public function storeSecret(Request $request, $id)
{
$user = User::findOrFail($id);
$user->fill([
'secret' => Crypt::encrypt($request->secret)
])->save();
}
}
~~~
#### **2.2 [解密](http://laravelacademy.org/tags/%e8%a7%a3%e5%af%86 "View all posts in 解密")**
当然,你可以使用`Crypt`门面上的`decrypt`方法进行解密。如果该值不能被解密,例如MAC无效,将会抛出一个`Illuminate\Contracts\Encryption\DecryptException`异常:
~~~
use Illuminate\Contracts\Encryption\DecryptException;
try {
$decrypted = Crypt::decrypt($encryptedValue);
} catch (DecryptException $e) {
//
}
~~~
- 序言
- 发行版本说明
- 升级指南
- 贡献代码
- 开始
- 安装
- 配置
- Laravel Homestead
- 基础
- HTTP 路由
- HTTP 中间件
- HTTP 控制器
- HTTP 请求
- HTTP 响应
- 视图
- Blade 模板引擎
- 架构
- 一次请求的生命周期
- 应用目录结构
- 服务提供者
- 服务容器
- 门面(Facades)
- 数据库
- 起步
- 查询构建器
- 迁移
- 填充数据
- Eloquent ORM
- 起步
- 关联关系
- 集合
- 访问器&修改器
- 序列化
- 服务
- 用户认证
- 用户授权
- Artisan Console
- 订阅支付实现:Laravel Cashier
- 缓存
- 集合
- 集成前端资源:Laravel Elixir
- 加密
- 错误&日志
- 事件
- 文件系统/云存储
- 哈希
- 辅助函数
- 本地化
- 邮件
- 包开发
- 分页
- Redis
- 队列
- Session
- Envoy Task Runner
- 任务调度
- 测试
- 验证
- 新手入门指南
- 简单任务管理系统
- 带用户功能的任务管理系统