我在这门课上有一个有点奇怪的:
<?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
丢失了,因为方法encrypt()
mcrypt_module_close( $this->_ch );
也许您可以更改__construct
并仅保存参数,只需在每次加密或解密时创建句柄(如_ch
)。
我不擅长 Mcrypt,所以也许比我更糟糕,但"有效 MCrypt 资源"问题的原因确实mcrypt_module_close
看起来像是命名空间问题,因为您没有在__construct()
中为MCRYPT_MODE_ECB
添加前缀。
这是要检查的东西,但由于我无法重现,不确定这是否是答案。
你有 SHA512(创建 512 长度的密钥),但算法需要 256 长度的密钥。如果使用 SHA256 有什么区别吗?通常,密钥不匹配应该会产生垃圾,但在这种情况下,它可能仍在"有副作用"的情况下工作。