/** * 构造函数 * * @param string 密钥 * @param string 模式 * @param string 向量("off":不使用 / "auto":自动 / 其他:指定值,长度同密钥) */ public function __construct($key, $mode = 'cbc', $iv = "off"){ switch (strlen($key)){ case 8: $this- mcrypt = MCRYPT_DES; break; case 16: $this- mcrypt = MCRYPT_RIJNDAEL_128; break; case 32: $this- mcrypt = MCRYPT_RIJNDAEL_256; break; default: die("Key size must be 8/16/32"); }
$this- key = $key;
switch (strtolower($mode)){ case 'ofb': $this- mode = MCRYPT_MODE_OFB; if ($iv == 'off') die('OFB must give a IV'); //OFB必须有向量 break; case 'cfb': $this- mode = MCRYPT_MODE_CFB; if ($iv == 'off') die('CFB must give a IV'); //CFB必须有向量 break; case 'ecb': $this- mode = MCRYPT_MODE_ECB; $iv = 'off'; //ECB不需要向量 break; case 'cbc': default: $this- mode = MCRYPT_MODE_CBC; }
switch (strtolower($iv)){ case "off": $this- iv = null; break; case "auto": $source = PHP_OS=='WINNT' ? MCRYPT_RAND : MCRYPT_DEV_RANDOM; $this- iv = mcrypt_create_iv(mcrypt_get_block_size($this- mcrypt, $this- mode), $source); break; default: $this- iv = $iv; }
}
/** * 获取向量值 * @param string 向量值编码(base64/hex/bin) * @return string 向量值 */ public function getIV($code = 'base64'){ switch ($code){ case 'base64': $ret = base64_encode($this- break; case 'hex': $ret = bin2hex($this- break; case 'bin': default: $ret = $this- } return $ret; }