mcrypt_encrypt添加了不需要的字节

时间:2014-08-25 15:38:23

标签: php encryption aes mcrypt

我尝试使用MCRYPT_RIJNDAEL_128算法加密某些数据。但不知何故,当我加密并随后解密时,解密数据随机添加了字节。

输入:string(13) "test@test.com"

输出:string(16) "test@test.com"

enter image description here

正如您所看到的,输出有16个字符,而输入有13个字符。

以下是用于加密的代码。

class Cipher
{

/**
 * The key/salt(bin2hex format) used to encrypt data with in AES(RIJNDAEL) format.
 * @var string
 */
private static $encryptionKey = 'baafbd1f8d752d920caae00ae550be8185c1183207a142c97c36fca3edc507da';

/**
 * Gets and transforms the encryption key to binary format.
 * @return string (in binary format)
 */
public static function getEncryptionKey()
{
    return hex2bin(self::$encryptionKey);
}

/**
 * Generates a new random main encryption key used to encrypt data.
 * Store the generated key in the private property of this class.
 * @param bool $strong Whether the encryption will be strong.
 * @return string The generated key in hexadecimal format.
 */
public static function generateEncryptionKey($strong = true)
{
    $keySize = mcrypt_get_key_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    return bin2hex(openssl_random_pseudo_bytes($keySize, $strong));
}

/**
 * Creates an encryption key IV used to store near the database record for the encrypted data.
 * Use bin2hex function for a representational string.
 * @return string (in binary format)
 */
public static function createIv()
{
    $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    return mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
}

/**
 * Encrypts a given string by the generated encryption key and generated IV.
 * @param string $string The string which will be encrypted.
 * @param string $iv The dynamic key used to encrypt.
 * @return string (in binary format)
 */
public static function encrypt($string, $iv)
{
    return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, self::getEncryptionKey(), $string, MCRYPT_MODE_CBC, $iv);
}

/**
 * Decrypts a given string by the generated encryption key and generated IV.
 * @param string $string The binary string which will be decrypted.
 * @param string $iv The dynamic key which belongs to the encrypted string.
 * @return string The decrypted string.
 */
public static function decrypt($string, $iv)
{
    return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, self::getEncryptionKey(), $string, MCRYPT_MODE_CBC, $iv);
}

}

此处显示的加密密钥未在生产或测试环境中使用,仅用于显示目的。

以下内容用于显示解密

$iv = Cipher::createIv();
$emailAddress = Cipher::encrypt('test@test.com', $iv);

var_dump(Cipher::decrypt($emailAddress, $iv));exit;

我使用以下环境:

Ubuntu:14.10

PHP:PHP 5.5.9-1ubuntu4.3(cli)(建于:2014年7月7日16:36:58)

1 个答案:

答案 0 :(得分:1)

这些只是在末尾添加填充0x00个字符,因为该加密算法的字符串长度必须是16的倍数(128位)。

确实,如果你在代码的末尾添加:

var_dump(bin2hex(Cipher::decrypt($emailAddress, $iv)));

你可以看到最后6个字符都是0(这意味着最后有3个0x00字节)。

要删除它们,只需运行:

$decrypted = rtrim($decrypted, "\0");