[TOC]
# 加密/解密
Phalcon通過`Phalcon\Crypt`組件提供加密功能。該類為[openssl](http://www.php.net/manual/en/book.openssl.php) PHP的加密庫提供了簡單的面向對象的包裝器。
默認情況下,此組件使用AES-256-CFB提供安全加密。
密碼AES-256用于Internet上的SSL/TLS中的其他位置。它被認為是頂級密碼之一。理論上它是不可破解的,因為密鑰的組合是巨大的。盡管NSA已將此分類在[Suite B](https://en.wikipedia.org/wiki/NSA_Suite_B_Cryptography)中,但他們還建議使用高于128位的密鑰進行加密。
>[warning] 您必須使用與當前算法相對應的密鑰長度。對于默認使用的算法,它是32個字節。
如果在對象構造期間未選擇用于計算摘要(簽名)的算法,則默認選擇aes-256-cfb。
## 基礎使用
該組件設計非常簡單易用:
```php
<?php
use Phalcon\Crypt;
// Create an instance
$crypt = new Crypt();
/**
* Set the cipher algorithm.
*
* The `aes-256-gcm' is the preferable cipher, but it is not usable until the
* openssl library is upgraded, which is available in PHP 7.1.
*
* The `aes-256-ctr' is arguably the best choice for cipher
* algorithm in these days.
*/
$crypt->setCipher('aes-256-ctr');
/**
* Set the encryption key.
*
* The `$key' should have been previously generated in a cryptographically safe way.
*
* Bad key:
* "le password"
*
* Better (but still unsafe):
* "#1dj8$=dp?.ak//j1V$~%*0X"
*
* Good key:
* "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3"
*
* Use your own key. Do not copy and paste this example key.
*/
$key = "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3";
$text = 'This is the text that you want to encrypt.';
$encrypted = $crypt->encrypt($text, $key);
echo $crypt->decrypt($encrypted, $key);
```
您還可以設置算法以及在對象構造期間是否計算消息的摘要(簽名)。這消除了調用`setCipher()`和`useSigning()`的需要:
```php
<?php
use Phalcon\Crypt;
// Create an instance
$crypt = new Crypt('aes-256-ctr', true);
$key = "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3";
$text = 'This is the text that you want to encrypt.';
$encrypted = $crypt->encrypt($text, $key);
echo $crypt->decrypt($encrypted, $key);
```
您可以使用相同的實例多次加密/解密:
```php
<?php
use Phalcon\Crypt;
$crypt->setCipher('aes-256-ctr');
// Create an instance
$crypt = new Crypt();
// Use your own keys!
$texts = [
"T4\xb1\x8d\xa9\x98\x054t7w!z%C*F-Jk\x98\x05\\\x5c" => 'This is a secret text',
"T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3" => 'This is a very secret',
];
foreach ($texts as $key => $text) {
// Perform the encryption
$encrypted = $crypt->encrypt($text, $key);
// Now decrypt
echo $crypt->decrypt($encrypted, $key);
}
```
為了更好的安全性,您可以指示組件根據 `getAvailableHashAlgos` 返回的受支持算法之一計算消息摘要。如上所示,該算法可以在對象實例化期間設置,但也可以在之后設置。
**注意** 默認情況下,Phalcon 4.0.0或更高版本將啟用計算消息摘要(簽名)。
```php
<?php
use Phalcon\Crypt;
// Create an instance
$crypt = new Crypt();
$crypt->setCipher('aes-256-ctr');
$crypt->setHashAlgo('aes-256-cfb');
// Force calculation of a digest of the message based on the Hash algorithm
$crypt->useSigning(true);
$key = "T4\xb1\x8d\xa9\x98\x054t7w!z%C*F-Jk\x98\x05\\\x5c";
$text = 'This is a secret text';
// Perform the encryption
$encrypted = $crypt->encrypt($text, $key);
// Now decrypt
echo $crypt->decrypt($encrypted, $key);
```
## 加密選項
以下選項可用于更改加密行為:
| 名稱 | 描述 |
| ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Cipher | 密碼是openssl支持的加密算法之一。你可以在[這里](http://www.php.net/manual/en/function.openssl-get-cipher-methods.php)看到一個列表|
案例:
```php
<?php
use Phalcon\Crypt;
// Create an instance
$crypt = new Crypt();
// Use blowfish
$crypt->setCipher('bf-cbc');
// Use your own key!
$key = "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3";
$text = 'This is a secret text';
echo $crypt->encrypt($text, $key);
```
如果要檢查系統支持的可用算法,可以調用 `getAvailableHashAlgos()` 方法。
```php
<?php
use Phalcon\Crypt;
// Create an instance
$crypt = new Crypt();
// Get the supported algorithms
$algorithms = $crypt->getAvailableHashAlgos();
var_dump($algorithms);
```
## Base64支持
為了正確傳輸(電子郵件)或顯示(瀏覽器)加密,[base64](http://www.php.net/manual/en/function.base64-encode.php)編碼通常應用于加密文本:
```php
<?php
use Phalcon\Crypt;
// Create an instance
$crypt = new Crypt();
// Use your own key!
$key = "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3";
$text = 'This is a secret text';
$encrypt = $crypt->encryptBase64($text, $key);
echo $crypt->decryptBase64($encrypt, $key);
```
## 設置加密服務
您可以在服務容器中設置加密組件,以便從應用程序的任何部分使用它:
```php
<?php
use Phalcon\Crypt;
$di->set(
'crypt',
function () {
$crypt = new Crypt();
// Set a global encryption key
$crypt->setKey(
"T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3"
);
return $crypt;
},
true
);
```
然后,例如,在控制器中,您可以按如下方式使用它:
```php
<?php
use Phalcon\Mvc\Controller;
class SecretsController extends Controller
{
public function saveAction()
{
$secret = new Secrets();
$text = $this->request->getPost('text');
$secret->content = $this->crypt->encrypt($text);
if ($secret->save()) {
$this->flash->success(
'Secret was successfully created!'
);
}
}
}
```
## 鏈接
* [Advanced Encryption Standard (AES)](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
* [What is block cipher](https://en.wikipedia.org/wiki/Block_cipher)
* [Introduction to Blowfish](http://www.splashdata.com/splashid/blowfish.htm)
* [CTR-Mode Encryption](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.79.1353&rep=rep1&type=pdf)
* [Recommendation for Block Cipher Modes of Operation: Methods and Techniques](https://csrc.nist.gov/publications/detail/sp/800-38a/final)
* [Counter (CTR) mode](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29)
- 常規
- Welcome
- 貢獻
- 生成回溯
- 測試重現
- 單元測試
- 入門
- 安裝
- Web服務器設置
- WAMP
- XAMPP
- 教程
- 基礎教程
- 教程:創建一個簡單的REST API
- 教程:V?kuró
- 提升性能
- 教程:INVO
- 開發環境
- Phalcon Compose (Docker)
- Nanobox
- Phalcon Box (Vagrant)
- 開發工具
- Phalcon開發者工具的安裝
- Phalcon開發者工具的使用
- 調試應用程序
- 核心
- MVC應用
- 微應用
- 創建命令行(CLI)應用程序
- 依賴注入與服務定位
- MVC架構
- 服務
- 使用緩存提高性能
- 讀取配置
- 上下文轉義
- 類加載器
- 使用命名空間
- 日志
- 隊列
- 數據庫
- 數據庫抽象層
- Phalcon查詢語言(PHQL)
- ODM(對象文檔映射器)
- 使用模型
- 模型行為
- ORM緩存
- 模型事件
- 模型元數據
- 模型關系
- 模型事務
- 驗證模型
- 數據庫遷移
- 分頁
- 前端
- Assets管理
- 閃存消息
- 表單
- 圖像
- 視圖助手(標簽)
- 使用視圖
- Volt:模板引擎
- 業務邏輯
- 訪問控制列表(ACL)
- 注解解析器
- 控制器
- 調度控制器
- 事件管理器
- 過濾與清理
- 路由
- 在session中存儲數據
- 生成URL和路徑
- 驗證
- HTTP
- Cookies管理
- 請求環境
- 返回響應
- 安全
- 加密/解密
- 安全
- 國際化
- 國際化
- 多語言支持