Encryption/Decryption

Phalcon通过 Phalcon\Crypt 组件提供了加密和解密工具。这个类提供了对PHP openssl 的封装。

默认情况下这个组件使用AES-256-CFB。

You must use a key length corresponding to the current algorithm. For the algorithm used by default it is 32 bytes.

基本使用

这个组件极易使用:

  1. <?php
  2. use Phalcon\Crypt;
  3. // Create an instance
  4. $crypt = new Crypt();
  5. $key = "This is a secret key (32 bytes).";
  6. $text = "This is the text that you want to encrypt.";
  7. $encrypted = $crypt->encrypt($text, $key);
  8. echo $crypt->decrypt($encrypted, $key);

也可以使用同一实例加密多次:

  1. <?php
  2. use Phalcon\Crypt;
  3. // 创建实例
  4. $crypt = new Crypt();
  5. $texts = [
  6. "my-key" => "This is a secret text",
  7. "other-key" => "This is a very secret",
  8. ];
  9. foreach ($texts as $key => $text) {
  10. // 加密
  11. $encrypted = $crypt->encrypt($text, $key);
  12. // 解密
  13. echo $crypt->decrypt($encrypted, $key);
  14. }

加密选项(Encryption Options)

下面的选项可以改变加密的行为:

名称描述
Ciphercipher是libmcrypt提供支持的一种加密算法。 查看这里 here

例子:

  1. <?php
  2. use Phalcon\Crypt;
  3. // 创建实例
  4. $crypt = new Crypt();
  5. // 使用 blowfish
  6. $crypt->setCipher("bf-cbc");
  7. $key = "le password";
  8. $text = "This is a secret text";
  9. echo $crypt->encrypt($text, $key);

提供 Base64(Base64 Support)

为了方便传输或显示我们可以对加密后的数据进行 base64 转码:

  1. <?php
  2. use Phalcon\Crypt;
  3. // 创建实例
  4. $crypt = new Crypt();
  5. $key = "le password";
  6. $text = "This is a secret text";
  7. $encrypt = $crypt->encryptBase64($text, $key);
  8. echo $crypt->decryptBase64($encrypt, $key);

配置加密服务(Setting up an Encryption service)

你也可以把加密组件放入服务容器中这样我们可以在应用中的任何一个地方访问这个组件:

  1. <?php
  2. use Phalcon\Crypt;
  3. $di->set(
  4. 'crypt',
  5. function () {
  6. $crypt = new Crypt();
  7. // 设置全局加密密钥
  8. $crypt->setKey(
  9. "%31.1e$i86e$f!8jz"
  10. );
  11. return $crypt;
  12. },
  13. true
  14. );

然后,例如,我们可以在控制器中使用它了:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class SecretsController extends Controller
  4. {
  5. public function saveAction()
  6. {
  7. $secret = new Secrets();
  8. $text = $this->request->getPost("text");
  9. $secret->content = $this->crypt->encrypt($text);
  10. if ($secret->save()) {
  11. $this->flash->success(
  12. "Secret was successfully created!"
  13. );
  14. }
  15. }
  16. }