php mcrypt_decrypt不考虑数据中的空字符

时间:2013-10-09 12:30:18

标签: php encryption

php mcrypt_decrypt在输入(密码)数据中不考虑 null 字符。 (显然它在null char的第一次并发时结束)。如何使用空字符解密数据?我不想使用base64 encoding,但无论如何它都无法工作,因为加密会输出空字符。

[编辑] 返回类型也是字符串,因此使用空字符的输出将被截断。这是怎么回事?或者我应该使用哪些其他加密库来操作缓冲区而不是字符串?

1 个答案:

答案 0 :(得分:0)

mcrypt库适用于包含\ 0字符的数据。也许你在其他地方丢失了一部分字符串,也许在打印结果之前使用字符串函数。

我只是仔细检查了这个例子,它在解密后返回\ 0个字符。如果需要AES加密,可以用MCRYPT_RIJNDAEL_256替换MCRYPT_TWOFISH。

/**
 * Encrypts data with the TWOFISH algorithm. The IV vector will be
 * included in the resulting binary string.
 * @param string $data Data to encrypt. Trailing \0 characters will get lost.
 * @param string $key This key will be used to encrypt the data. The key
 *   will be hashed to a binary representation before it is used.
 * @return string Returns the encrypted data in form of a binary string.
 */
public static function encryptTwofish($data, $key)
{
  if (!defined('MCRYPT_DEV_URANDOM')) throw new Exception('The MCRYPT_DEV_URANDOM source is required (PHP 5.3).');
  if (!defined('MCRYPT_TWOFISH')) throw new Exception('The MCRYPT_TWOFISH algorithm is required (PHP 5.3).');

  // The cbc mode is preferable over the ecb mode
  $td = mcrypt_module_open(MCRYPT_TWOFISH, '', MCRYPT_MODE_CBC, '');

  // Twofish accepts a key of 32 bytes. Because usually longer strings
  // with only readable characters are passed, we build a binary string.
  $binaryKey = hash('sha256', $key, true);

  // Create initialization vector of 16 bytes
  $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_URANDOM);

  mcrypt_generic_init($td, $binaryKey, $iv);
  $encryptedData = mcrypt_generic($td, $data);
  mcrypt_generic_deinit($td);
  mcrypt_module_close($td);

  // Combine iv and encrypted text
  return $iv . $encryptedData;
}

/**
 * Decrypts data, formerly encrypted with @see encryptTwofish.
 * @param string $encryptedData Binary string with encrypted data.
 * @param string $key This key will be used to decrypt the data.
 * @return string Returns the original decrypted data.
 */
public static function decryptTwofish($encryptedData, $key)
{
  if (!defined('MCRYPT_TWOFISH')) throw new Exception('The MCRYPT_TWOFISH algorithm is required (PHP 5.3).');

  $td = mcrypt_module_open(MCRYPT_TWOFISH, '', MCRYPT_MODE_CBC, '');

  // Extract initialization vector from encrypted data
  $ivSize = mcrypt_enc_get_iv_size($td);
  $iv = substr($encryptedData, 0, $ivSize);
  $encryptedData = substr($encryptedData, $ivSize);

  $binaryKey = hash('sha256', $key, true);

  mcrypt_generic_init($td, $binaryKey, $iv);
  $decryptedData = mdecrypt_generic($td, $encryptedData);
  mcrypt_generic_deinit($td);
  mcrypt_module_close($td);

  // Original data was padded with 0-characters to block-size
  return rtrim($decryptedData, "\0");
}