テキストを可逆的な暗号化する Crypt_Blowfish

暗号化キーを使って、テキストを暗号化&複合化するPEARです。

[参考記事] ブロック暗号とは
[参考記事] PHPで暗号化・複合化を行う ブロック暗号

Crypt_Blowfish

インストール

pear install Crypt_Blowfish

PEARに追加インストールできない場合には、インクルードパスの追加で対応できます。

set_include_path(
  realpath(dirname(__FILE__) .DIRECTORY_SEPARATOR.'vendor' .DIRECTORY_SEPARATOR)
  . PATH_SEPARATOR .
  get_include_path());

Crypt_Blowfishには、mcryptが必要です。
libmcryptをインストールし、configureオプションに「--with-mcrypt」を付ける必要があります。
また、PHP5以降、libmcrypt 2.5.6以降が必要です。

サンプルコード

include_once 'Crypt/Blowfish.php';
$key = '【暗号化キー】';
$text = '【暗号化する文言】';

// Blowfishに暗号化キーを渡し、オブジェクトを生成する
$blowfish = new Crypt_Blowfish($key);

// 暗号化されたテキストを得る
$encrypt = $blowfish->encrypt($text);

// 暗号化されたテキストを得る
$decrypt = $blowfish->decrypt($encrypt);

Crypt_Blowfishのバグ

複数回オブジェクトを生成すると、エラー『 The key is not initialized. 』が出る。

$blowfish = new Crypt_Blowfish($key);
$encrypt = $blowfish->encrypt($text);

$blowfish = new Crypt_Blowfish($key);
$decrypt = $blowfish->decrypt($encrypt);

Bug #9638 Double calls to decrypt() method with same key do not reinitialize the _P array

2008年8月30日時点で修正されています。(1.1.0RC2以降)

OpenPNEでの使用例

// 下位互換のBlowfishを使うかどうか
define("OPENPNE_USE_OLD_CRYPT_BLOWFISH",false);

// 暗号化キー
define("ENCRYPT_KEY",false);


function &get_crypt_blowfish()
{
    static $singleton;
    if (empty($singleton)) {
        if (OPENPNE_USE_OLD_CRYPT_BLOWFISH) {
            include_once 'Crypt/BlowfishOld.php';
            $singleton = new Crypt_BlowfishOld(ENCRYPT_KEY);
        } else {
            include_once 'Crypt/Blowfish.php';
            $singleton = new Crypt_Blowfish(ENCRYPT_KEY);
        }
    }
    return $singleton;
}

/**
 * 可逆的な暗号化をする
 *
 * @param string $str 平文
 * @return string 暗号文
 */
function t_encrypt($str)
{
    if (!$str) return '';

    $bf =& get_crypt_blowfish();
    $str = $bf->encrypt($str);

    //base64
    $str = base64_encode($str);

    return $str;
}

/**
 * 可逆的な暗号を復号化する
 *
 * @param string $str 暗号文
 * @return string 平文
 */
function t_decrypt($str)
{
    if (!$str) return '';

    //base64
    $str = base64_decode($str);

    $bf =& get_crypt_blowfish();
    return rtrim($bf->decrypt($str));
}

関連記事

スポンサーリンク

Excelの日付が数字になるときの対処法

ホームページ製作・web系アプリ系の製作案件募集中です。

上に戻る