2.40 Encryption/Decryption
加密/解密
Phalcon provides encryption facilities via thePhalcon\Crypt
component. This class offers simple object-oriented wrappers to themcrypt
php’s encryption library.
By default, this component provides secure encryption using AES-256 (rijndael-256-cbc).
Phalcon通过\Phalcon\Crypt组件提供了加密和解密工具。这个类提供了一个面象对象的对php mcrypt的封封装类。默认情况下这个组件使用AES-256 加密方式。
2.40.1 Basic Usage
基本使用
This component is designed to provide a very simple usage:
这个组件可以使用极简单的使用:
<?php
//Create an instance
$crypt=
newPhalcon\Crypt();
$key=
’le password’;//密钥
$text=
’This is a secret text’;//待加密的文本
$encrypted
= $crypt->encrypt($text,$key);//执行加密操作
echo$crypt->decrypt($encrypted,$key);//解密操作
You can use the same instance to encrypt/decrypt several times:
也可以使用同一实例加密多次:
<?php
//Create an instance
$crypt=
newPhalcon\Crypt();
$texts =array(
’my-key’ =>’This is a secret text’,
’other-key’
=> ’This is a very secret’
);
foreach($textsas
$key=>
$text) {
//Perform the encryption
$encrypted
= $crypt->encrypt($text,$key);
//Now decrypt
echo$crypt->decrypt($encrypted,$key);
}
2.40.2 Encryption Options
加密选项
Example(例子):
<?php
//Create an instance//创建实例
$crypt=
newPhalcon\Crypt();
//Use blowfish
$crypt->setCipher(’blowfish’);
$key=
’le password’;
$text=
’This is a secret text’;
echo$crypt->encrypt($text,‘’);
2.40.3 Base64 Support
Base64支持
In order that encryption is properly transmitted (emails) or displayed (browsers)base64
encoding is usually applied to encrypted texts:
为了方便传输或显示我们可以对加密后的数据进行base64转码
<?php
//Create an instance
$crypt=
newPhalcon\Crypt();
$key=
’le password’;
$text=
’This is a secret text’;
$encrypt =$crypt->encryptBase64($text,$key);
echo$crypt->decryptBase64($text,$key);
2.40.4 Setting up an Encryption service
设置加密服务
You can set up the encryption component in the services container in order to use it from any part of the application:
你也可以把加密组件放入服务器容器中这样我们可以在应用中任何一个地方访问这个组件:
<?php
$di->set(’crypt’,function()
{
$crypt=
newPhalcon\Crypt();
//Set a global encryption key
$crypt->setKey(’%31.1e$i86e$f!8jz’);
return $crypt;
},true);
Then, for example, in a controller you can use it as follows:
然后我们就可以像如下这样使用加密组件了:
<?php
usePhalcon\Mvc\Controller;
classSecretsController
extendsController
{
public function
saveAction()
{
$secret=
newSecrets();
$text=
$this->request->getPost(’text’);
$secret->content=
$this->crypt->encrypt($text);
if($secret->save())
{
$this->flash->success(’Secret
was successfully created!’);
}
}
}