Rijndael 256位加密/解密会引发错误

时间:2014-01-07 14:52:25

标签: php encryption

我有以下课程。

<?php
/**
 * Cypher Class
 */
class Cipher
{
    /**
     * SHA256 Encrypted Key
     * @var string
     */
    private $encryptedKey;
    /**
     * Initial vector
     *
     * Used to seed the encryption string
     * 
     * @var string
     */
    private $initVector;

    /**
     * Constructor
     * @param boolean|string $personalKey Holds the personal key to use in encryption
     */
    public function __construct($personalKey = false)
    {
        // $config = configuration::getInstance();
        if (false === $personalKey) {
            return false;
        } else {
            $key = $personalKey;
        }

        $this->encryptionKey = hash('sha256', $key, TRUE);
        $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CFB);
        $this->initVector = mcrypt_create_iv($size, MCRYPT_DEV_URANDOM);
    }
    /**
     * Encrypt a string
     * @param  mixed $input  Data to encrypt
     * @return string        Encrypted data
     */
    public function encrypt($input)
    {
        return array(
            'salt' => base64_encode($this->initVector),
            'encrypted_value' => base64_encode(mcrypt_encrypt(
                MCRYPT_RIJNDAEL_256,
                $this->encryptionKey,
                $input,
                MCRYPT_MODE_CFB,
                $this->initVector
        )));
    }

    /**
     * Decrypt string
     * @param  string $input Encrypted string we are going to decrypt
     * @param  string $salt Encrypted salt used to decrypt
     * @return string        Decrypted output
     */
    public function decrypt($input, $salt)
    {
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->encryptionKey, base64_decode($input), MCRYPT_MODE_CFB, $salt));
    }
}

我的IV和加密字符串都是16个字节,但由于某种原因,PHP给了我以下错误:

Warning: mcrypt_encrypt(): The IV parameter must be as long as the blocksize in C:\xampp\htdocs\public\cipher\Cipher.php on line 58

我不是加密中的明星,所以我想知道你们中的一个好人是否可以帮助我。

1 个答案:

答案 0 :(得分:1)

IV的大小与密码的block size有关。所以无论你选择什么,块大小都必须用作IV的长度。

Rijndael支持128,160,192,224和256位的块大小。如果您使用MCRYPT_RIJNDAEL_128,那么您使用的是128位块大小(与AES匹配)。如果您使用MCRYPT_RIJNDAEL_256,那么您的块大小将是原来的两倍。

因此,您必须确定要使用的块大小,并确保代码始终引用相同的MCRYPT_RIJNDAEL_*常量。

我认为网站给你一个错误,因为它期望一个16字节的块大小(根据AES)。