MHashによるハッシュの作成
MHashは無料のライブラリで、開発者は数多くのハッシュアルゴリズムから使用するものを選べます。これらのアルゴリズムを使用して、チェックサムの計算、メッセージダイジェストの作成、他の署名の作成を行うことができます。
Libmhashのインストール
- libmhash.dllをダウンロードします。
- libmhash.dllファイルを{php_home}/extと{Windows_home}/System32にコピーします。
- php.ini内のextension=php_mhash.dllという行のコメント記号(;)を削除し、この行を有効にします。
- 更新したphp.iniファイルを保存します。
サポート対象ハッシュ
MHashが現在サポートするハッシュは次のとおりです。
- MHASH_ADLER32
- MHASH_CRC32
- MHASH_CRC32B
- MHASH_GOST
- MHASH_HAVAL128
- MHASH_HAVAL160
- MHASH_HAVAL192
- MHASH_HAVAL256
- MHASH_MD4
- MHASH_MD5
- MHASH_RIPEMD160
- MHASH_SHA1
- MHASH_SHA256
- MHASH_TIGER
- MHASH_TIGER128
- MHASH_TIGER160
次の例では、MHashを使ってtextfile.txtの暗号化を行い、その結果をencrypted.txtに書き込んでいます。
<?php $file = 'textfile.txt'; $initial_contents = file_get_contents($file); if($initial_contents){ //mhash() applies a hash function specified by MHASH_MD5 //to the $initial_contents $encrypted = mhash(MHASH_MD5, $initial_contents); // get current Unix timestamp $current = time(); $salt = $current; $password = "Octavia"; //mhash_keygen_s2k generates a key according to the hash function //given and the password provided by the user. $hash = mhash_keygen_s2k(MHASH_GOST, $password, $salt, 20); //concatenate the $salt with the $hash $key = $salt . "|" . bin2hex($hash); $encrypted_file = @fopen('encrypted.txt','w'); $ok_encrypt = @fwrite($encrypted_file, 'mhash: '.bin2hex($encrypted).' mhash_keygen_s2k: '.$key); if($ok_encrypt){ echo 'The encrypted code was succesfully created '. 'in encrypted_file.txt !!!'.'<br />'; } else{ echo ("The write of this file failed!"); } @fclose($encrypted_file); } ?>
秘密鍵とCrypt_Blowfish
秘密鍵暗号方式では、1つの鍵を暗号化と復号の両方に使用します。このため「対称鍵」とも呼ばれます。例えば、一般的に使われるDESアルゴリズムは秘密鍵アルゴリズムです。Crypt_Blowfish PEARパッケージは、Blowfishブロック暗号に基づいており、秘密鍵あり/なしの双方向の暗号化に対応しています。Crypt_BlowfishパッケージはMCryptを必要としませんが、インストールされていれば使用できます。最新のリリースバージョンは1.0.1(安定版)です。インストール方法は、他のPEARパッケージと同様です。
> pear install pear_package_name
このパッケージは、Blowfish.phpファイル内に定義されている2つのクラスを使用します。そのため、Crypt_Blowfishパッケージを使用するすべてのスクリプトでBlowfish.phpファイルをインクルードしておく必要があります。
require_once 'Crypt/Blowfish.php';
先ほどの例と同じ処理をする暗号化プログラムをCrypt_Blowfishで実装したコードを次に示します。
<?php require_once 'Crypt/Blowfish.php'; $file = 'textfile.txt'; $initial_contents = file_get_contents($file); if($initial_contents){ $bf = new Crypt_Blowfish('some secret key!'); // Encrypts a string $encrypted = $bf->encrypt($initial_contents); $encrypted_file = @fopen('encrypted.txt','w'); $ok_encrypt = @fwrite($encrypted_file,$encrypted); if($ok_encrypt){ echo 'The encrypted code was succesfully created '. 'in encrypted_file.txt!!!'.'<br />'; } else{ echo ("The write of this file failed!"); } @fclose($encrypted_file); // Decrypts an encrypted string $plaintext = $bf->decrypt($encrypted); $newfile = @fopen('newfile.txt','w'); $ok_decrypt = @fwrite($newfile,$plaintext); if($ok_decrypt){ echo 'The decrypted code was succesfully created '. 'in newfile.txt!!!'.'<br />'; } else{ echo ("The write of this file failed!"); } @fclose($newfile); } ?>
