加密过滤器

mcrypt.*mdecrypt.*使用 libmcrypt 提供了对称的加密和解密。这两组过滤器都支持 mcrypt 扩展库中相同的算法,格式为 mcrypt.ciphername,其中 ciphername是密码的名字,将被传递给 mcrypt_module_open()。有以下五个过滤器参数可用:

mcrypt 过滤器参数
参数 是否必须 默认值 取值举例
mode 可选 cbc cbc, 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 字节的二进制数据。根据密码而定

Example #1 用 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);
?>

Example #2 读取加密的文件

<?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;
?>
add a note add a note

User Contributed Notes 1 note

up
1
Uwe Ohse
1 month ago
1) The mcrypt module has been deprecated with PHP 7.1.
What does that mean for the encryption filters?

2) deriving the IV from the secret passphrase seems wrong. This leaks information about the passphrase without need.

3) using md5() for this? Really? hash() has been available since PHP 5.1.2.

4) hashing the passphrase twice does not add any security.

5) using substr() on binary data (why, oh why, is true passed to md5()?) might lead to headaches if mbstring.func_overload is used.
To Top