加密過濾器

加密過濾器特別適用于文件/數(shù)據(jù)流的加密。

mcrypt.* 和 mdecrypt.*

警告

本特性已自 PHP 7.1.0 起廢棄。強(qiáng)烈建議不要使用本特性。

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

mcrypt 過濾器參數(shù)
參數(shù) 是否必須 默認(rèn)值 取值舉例
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 字節(jié)的二進(jìn)制數(shù)據(jù)。根據(jù)密碼而定
key 必須 N/A 典型為 8,16 或 32 字節(jié)的二進(jìn)制數(shù)據(jù)。根據(jù)密碼而定

示例 #1 用 Blowfish 算法加解密

<?php
// 假設(shè)之前已經(jīng)生成了 $key
$iv_size mcrypt_get_iv_size(MCRYPT_BLOWFISHMCRYPT_MODE_CBC);
$iv mcrypt_create_iv($iv_sizeMCRYPT_DEV_URANDOM);
$fp fopen('encrypted-file.enc''wb');
fwrite($fp$iv);
$opts = array('mode'=>'cbc','iv'=>$iv'key'=>$key);
stream_filter_append($fp'mcrypt.blowfish'STREAM_FILTER_WRITE$opts);
fwrite($fp'message to encrypt');
fclose($fp);

// 解密
$fp fopen('encrypted-file.enc''rb');
$iv fread($fp$iv_size mcrypt_get_iv_size(MCRYPT_BLOWFISHMCRYPT_MODE_CBC));
$opts = array('mode'=>'cbc','iv'=>$iv'key'=>$key)
stream_filter_append($fp'mdecrypt.blowfish'STREAM_FILTER_READ$opts);
$data rtrim(stream_get_contents($fp));//trims off null padding
fclose($fp);
echo 
$data;
?>

示例 #2 將文件以 SHA256 HMAC 的 AES-128 CBC 加密

<?php
AES_CBC
::encryptFile($password"plaintext.txt""encrypted.enc");
AES_CBC::decryptFile($password"encrypted.enc""decrypted.txt");

class 
AES_CBC
{
   protected static 
$KEY_SIZES = array('AES-128'=>16,'AES-192'=>24,'AES-256'=>32);
   protected static function 
key_size() { return self::$KEY_SIZES['AES-128']; } //default AES-128
   
public static function encryptFile($password$input_stream$aes_filename){
      
$iv_size mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128MCRYPT_MODE_CBC);
      
$fin fopen($input_stream"rb");
      
$fc fopen($aes_filename"wb+");
      if (!empty(
$fin) && !empty($fc)) {
         
fwrite($fcstr_repeat("_"32) );//placeholder, SHA256 HMAC will go here later
         
fwrite($fc$hmac_salt mcrypt_create_iv($iv_sizeMCRYPT_DEV_URANDOM));
         
fwrite($fc$esalt mcrypt_create_iv($iv_sizeMCRYPT_DEV_URANDOM));
         
fwrite($fc$iv mcrypt_create_iv($iv_sizeMCRYPT_DEV_URANDOM));
         
$ekey hash_pbkdf2("sha256"$password$esalt$it=1000self::key_size(), $raw=true);
         
$opts = array('mode'=>'cbc''iv'=>$iv'key'=>$ekey);
         
stream_filter_append($fc'mcrypt.rijndael-128'STREAM_FILTER_WRITE$opts);
         
$infilesize 0;
         while (!
feof($fin)) {
            
$block fread($fin8192);
            
$infilesize+=strlen($block);
            
fwrite($fc$block);
         }
         
$block_size mcrypt_get_block_size(MCRYPT_RIJNDAEL_128MCRYPT_MODE_CBC);
         
$padding $block_size - ($infilesize $block_size);//$padding is a number from 1-16
         
fwrite($fcstr_repeat(chr($padding), $padding) );//perform PKCS7 padding
         
fclose($fin);
         
fclose($fc);
         
$hmac_raw self::calculate_hmac_after_32bytes($password$hmac_salt$aes_filename);
         
$fc fopen($aes_filename"rb+");
         
fwrite($fc$hmac_raw);//overwrite placeholder
         
fclose($fc);
      }
   }
   public static function 
decryptFile($password$aes_filename$out_stream) {
      
$iv_size mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128MCRYPT_MODE_CBC);
      
$hmac_raw file_get_contents($aes_filenamefalseNULL,  032);
      
$hmac_salt file_get_contents($aes_filenamefalseNULL32$iv_size);
      
$hmac_calc self::calculate_hmac_after_32bytes($password$hmac_salt$aes_filename);
      
$fc fopen($aes_filename"rb");
      
$fout fopen($out_stream'wb');
      if (!empty(
$fout) && !empty($fc) && self::hash_equals($hmac_raw,$hmac_calc)) {
         
fread($fc32+$iv_size);//skip sha256 hmac and salt
         
$esalt fread($fc$iv_size);
         
$iv    fread($fc$iv_size);
         
$ekey hash_pbkdf2("sha256"$password$esalt$it=1000self::key_size(), $raw=true);
         
$opts = array('mode'=>'cbc''iv'=>$iv'key'=>$ekey);
         
stream_filter_append($fc'mdecrypt.rijndael-128'STREAM_FILTER_READ$opts);
         while (!
feof($fc)) {
            
$block fread($fc8192);
            if (
feof($fc)) {
               
$padding ord($block[strlen($block) - 1]);//assume PKCS7 padding
               
$block substr($block00-$padding);
            }
            
fwrite($fout$block);
         }
         
fclose($fout);
         
fclose($fc);
      }
   }
   private static function 
hash_equals($str1$str2) {
      if(
strlen($str1) == strlen($str2)) {
         
$res $str1 $str2;
         for(
$ret=0,$i strlen($res) - 1$i >= 0$i--) $ret |= ord($res[$i]);
         return !
$ret;
      }
      return 
false;
   }
   private static function 
calculate_hmac_after_32bytes($password$hsalt$filename) {
      static 
$init=0;
      
$init or $init stream_filter_register("user-filter.skipfirst32bytes""FileSkip32Bytes");
      
$stream 'php://filter/read=user-filter.skipfirst32bytes/resource=' $filename;
      
$hkey hash_pbkdf2("sha256"$password$hsalt$iterations=100024$raw=true);
      return 
hash_hmac_file('sha256'$stream$hkey$raw=true);
   }
}
class 
FileSkip32Bytes extends php_user_filter
{
   private 
$skipped=0;
   function 
filter($in$out, &$consumed$closing)  {
      while (
$bucket stream_bucket_make_writeable($in)) {
         
$outlen $bucket->datalen;
         if (
$this->skipped<32){
            
$outlen min($bucket->datalen,32-$this->skipped);
            
$bucket->data substr($bucket->data$outlen);
            
$bucket->datalen $bucket->datalen-$outlen;
            
$this->skipped+=$outlen;
         }
         
$consumed += $outlen;
         
stream_bucket_append($out$bucket);
      }
      return 
PSFS_PASS_ON;
   }
}
class 
AES_128_CBC extends AES_CBC {
   protected static function 
key_size() { return self::$KEY_SIZES['AES-128']; }
}
class 
AES_192_CBC extends AES_CBC {
   protected static function 
key_size() { return self::$KEY_SIZES['AES-192']; }
}
class 
AES_256_CBC extends AES_CBC {
   protected static function 
key_size() { return self::$KEY_SIZES['AES-256']; }
}