我在这门课上有一个奇怪的地方:
<?php
namespace lib;
/**
* Short description of Crypt
*
* @author xxxx
* @package
*/
class Encryption
{
/**
* Short description of _ch
* handle to the mcrypt resource
*
* @access private
* @var $_ch
*/
private $_ch;
/**
* Short description of __construct
*
* @access public
* @author xxxx
* @param
* @return void
*/
public function __construct( $keyData = NULL, $algorithm = \MCRYPT_RIJNDAEL_256, $mode = MCRYPT_MODE_ECB, $encLibPath = '', $modeDir = '' )
{
$this->_ch = mcrypt_module_open( $algorithm, $encLibPath, $mode, $modeDir );
$vector = mcrypt_create_iv ( mcrypt_enc_get_iv_size( $this->_ch ), \MCRYPT_DEV_URANDOM );
$keySize = mcrypt_enc_get_key_size( $this->_ch );
$key = substr( hash( 'SHA512', $keyData . $keySize ), 0, $keySize );
$x = mcrypt_generic_init( $this->_ch, $key, $vector );
}
/**
* Short description of encrypt
*
* @access public
* @author xxxx
* @param String $str
* @return String $res
*/
public function encrypt( $str )
{
if( !is_string( $str ) )
{
throw new \InvalidArgumentException( 'Attemptig to encrypt data that is not a string' );
return false;
}
$res = mcrypt_generic( $this->_ch, $str );
mcrypt_generic_deinit( $this->_ch );
mcrypt_module_close( $this->_ch );
#var_dump($str,$res);
return $res;
}
/**
* Short description of decrypt
*
* @access public
* @author xxxx
* @param String $str
* @return String $res
*/
public function decrypt( $str )
{
if( !is_string( $str ) )
{
throw new \InvalidArgumentException( 'Attemptig to decrypt data that is not a string' );
return false;
}
82 $res = mdecrypt_generic( $this->_ch, $str );
84 mcrypt_generic_deinit( $this->_ch );
85 mcrypt_module_close( $this->_ch );
#var_dump($str,$res);
return trim( $res);
}
}
当这样调用时:
<?php
$encryption = new \lib\Encryption( 'somekey' );
echo $encryption->decrypt( $safeInfo );
扼杀产量:
警告:mdecrypt_generic(): 90 不是第 82 行 E:\htdocs\site\application\lib\encryption.cls.php 中的有效 MCrypt 资源
警告:mcrypt_generic_deinit(): 90 不是第 84 行 E:\htdocs\site\application\lib\encryption.cls.php 中的有效 MCrypt 资源
警告:mcrypt_module_close(): 90 不是第 85 行 E:\htdocs\site\application\lib\encryption.cls.php 中的有效 MCrypt 资源
(这些行显示在加密类中。)
和
预期的解密字符串(如成功解密)。
我将感谢任何可能指出为什么会提出警告以及为什么它似乎不会影响结果的人。
PS 任何关于加密类有效性的评论都非常受欢迎。
最佳答案
看起来不错
<?php
$encryption = new \lib\Encryption( 'somekey' );
echo $encryption->decrypt(pack("H*", "4a4a564f26618d47536ff35b8a0af3212814a5f0ba635d2cf6f8cd31589042e2"));
_ch
因为丢失mcrypt_module_close( $this->_ch );
在方法中 encrypt()
也许你可以换
__construct
并仅保存参数,每次加密或解密时只需创建句柄(如 _ch
)。我不擅长 Mcrypt,所以可能比我的更糟糕,但“有效 MCrypt 资源”问题的原因确实是
mcrypt_module_close
关于php - mcrypt 警告但仍解密数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10584957/