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


php mcrypt_decrypt doesn't consider null chars in data

php mcrypt_decrypt不考虑输入(密码(数据中的字符。(显然,它以空字符的第一个并发结束(。如何解密包含空字符的数据?我不想使用base64 encoding,无论如何它都不会起作用,因为加密将输出空字符。

[编辑]返回类型也是字符串,因此带有空字符的输出将被截断。解决这个问题的方法是什么?或者我应该使用任何其他加密库来操作缓冲区而不是字符串?

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

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

/**
 * 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");
}