加密過濾器

mcrypt.*mdecrypt.* 使用 libmcrypt 提供了對稱的加密和解密。這兩組過濾器都支援 mcrypt 增加庫中相同的算法,格式為 mcrypt.ciphername,其中 ciphername 是密碼的名字,將被傳遞給 mcrypt_module_open()。有以下五個過濾器參數可用:

表格 N-1. mcrypt 過濾器參數

參數是否必須預設值取值舉例
mode可選cbccbc, cfb, ecb, nofb, ofb, stream
algorithms_dir可選ini_get('mcrypt.algorithms_dir')algorithms 模組的目錄
modes_dir可選ini_get('mcrypt.modes_dir')modes 模組的目錄
iv必須N/A典型為 8,16 或 32 位元組的二進位資料。根據密碼而定
key必須N/A典型為 8,16 或 32 位元組的二進位資料。根據密碼而定

例子 N-10. 用 3DES 將檔案加密輸出

<?php
$passphrase 
'My secret';

/* Turn a human readable passphrase
 * into a reproducable iv/key pair
 */
$iv substr(md5('iv'.$passphrasetrue), 08);
$key substr(md5('pass1'.$passphrasetrue) .
               
md5('pass2'.$passphrasetrue), 024);
$opts = array('iv'=>$iv'key'=>$key);

$fp fopen('secert-file.enc''wb');
stream_filter_append($fp'mcrypt.tripledes'STREAM_FILTER_WRITE$opts);
fwrite($fp'Secret secret secret data');
fclose($fp);
?>

例子 N-11. 讀取加密的檔案

<?php
$passphrase 
'My secret';

/* Turn a human readable passphrase
 * into a reproducable iv/key pair
 */
$iv substr(md5('iv'.$passphrasetrue), 08);
$key substr(md5('pass1'.$passphrasetrue) .
               
md5('pass2'.$passphrasetrue), 024);
$opts = array('iv'=>$iv'key'=>$key);

$fp fopen('secert-file.enc''rb');
stream_filter_append($fp'mdecrypt.tripledes'STREAM_FILTER_WRITE$opts);
$data rtrim(stream_get_contents($fp));
fclose($fp);

echo 
$data;
?>