Documentation

目次

前のトピックへ

< セキュリティ

次のトピックへ

アクセス制御リスト ACL >

このページ

暗号化/復号化

Phalcon provides encryption facilities via the Phalcon\Crypt component. This class offers simple object-oriented wrappers to the mcrypt php’s encryption library.

By default, this component provides secure encryption using AES-256 (rijndael-256-cbc).

基本的な使い方

This component is designed to provide a very simple usage:

<?php

//Create an instance
$crypt = new Phalcon\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 = new Phalcon\Crypt();

$texts = array(
    'my-key' => 'This is a secret text',
    'other-key' => '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);
}

暗号化オプション

The following options are available to change the encryption behavior:

Name Description
Cipher The cipher is one of the encryption algorithms supported by libmcrypt. You can see a list here
Mode One of the encryption modes supported by libmcrypt (ecb, cbc, cfb, ofb)

Example:

<?php

//Create an instance
$crypt = new Phalcon\Crypt();

//Use blowfish
$crypt->setCipher('blowfish');

$key = 'le password';
$text = 'This is a secret text';

echo $crypt->encrypt($text, $key);

Base64 サポート

In order that encryption is properly transmited (emails) or displayed (browsers) base64 encoding is usually applied to encrypted texts:

<?php

//Create an instance
$crypt = new Phalcon\Crypt();

$key = 'le password';
$text = 'This is a secret text';

$encrypt = $crypt->encryptBase64($text, $key);

echo $crypt->decryptBase64($text, $key);

暗号化サービスのセットアップ

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 = new Phalcon\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

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!');
        }

    }

}