【问题标题】:Strings no longer equal after encryption and decryption加密和解密后字符串不再相等
【发布时间】:2011-05-09 09:01:44
【问题描述】:

我使用下面的类来加密和解密一个字符串。创建两个相同的字符串后,我对其中一个字符串进行加密,然后对其进行解密。但是,解密后的字符串不再等于它的孪生字符串(即使它们在转换后的文本形式中看起来相同)。此外,在获取加密解密字符串及其孪生并将它们转换为十六进制使用 bin2hex 之后,我发现它们看起来相似,只是之前加密的字符串末尾的加法数为零。

谁能指出我做错了什么?先感谢您。

类 proCrypt {

public function __set( $name, $value )
{
    switch( $name)
    {
        case 'key':
        case 'ivs':
        case 'iv':
        $this->$name = $value;
        break;

        default:
        throw new Exception( "$name cannot be set" );
    }
}

/**
*
* Gettor - This is called when an non existant variable is called
*
* @access    public
* @param    string    $name
*
*/
public function __get( $name )
{
    switch( $name )
    {
        case 'key':
        return 'abcd';

        case 'ivs':
        return mcrypt_get_iv_size( MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB );

        case 'iv':
        return mcrypt_create_iv( $this->ivs );

        default:
        throw new Exception( "$name cannot be called" );
    }
}

/**
*
* Encrypt a string
*
* @access    public
* @param    string    $text
* @return    string    The encrypted string
*
*/
public function encrypt( $text )
{
    // add end of text delimiter
    $data = mcrypt_encrypt( MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv );
    return bin2hex($data);
}

/**
*
* Decrypt a string
*
* @access    public
* @param    string    $text
* @return    string    The decrypted string
*
*/
public function decrypt( $text )
{
    $text = pack("H*" , $text);
    return mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv );
}

} // 课程结束

【问题讨论】:

  • 你能告诉我们每个的 var_dump() 吗? (未处理的和已经加解密的?)
  • 嗨,thegreasyitalian 我创建了两个字符串:$text1 = 'money'; $text2 = '钱';在加密和解密 $text2 并将两个文本转换为十六进制(bin2hex)后,我得到以下输出: text1: 6d6f6e6579 text2: 6d6f6e65790000000000000000000000
  • 对两个字符串都使用 var_dump($text1) 而不是 echo,看看会输出什么。
  • 感谢 bin2hex 输出。在 bin2hex 之前,只使用 var_dump() 呢?
  • 我得到了这个: text1: string(5) "money" text2: string(16) "money"

标签: php character-encoding encryption mcrypt


【解决方案1】:

加密算法通常要求输入是某个长度(8 字节、16 字节等)的倍数,才能使用其固定的“块大小”。您的输入字符串可能已填充 0 以匹配。您可以通过根据您选择的算法跟踪必要的填充来撤消它(每个算法都有自己的块大小和填充方法),并在解密后撤消它。

【讨论】:

    【解决方案2】:

    大概你有一个用空格填充的 16 长字符串。在 bin2hex() 之前尝试 trim() 以消除前导和尾随空格。

    【讨论】:

    • 效果很好!我只是使用 trim(text2) ,结果很好。非常感谢。
    • 没问题。注意,如果要处理的字符串有空格和开头或结尾,trim() 函数会删除它们。因此,这取决于您确保您的数据不需要保留那些前导或尾随空格。
    猜你喜欢
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 2015-11-24
    • 2010-12-27
    相关资源
    最近更新 更多