0

phpは、入力 (暗号化) データのヌルmcrypt_decrypt文字を考慮しません。(明らかに、null char の最初の同時発生で終了します)。null 文字を含むデータを復号化する方法は? 暗号化によってヌル文字が出力されるため、使用したくありません。とにかく機能しません。base64 encoding

[編集] 戻り値の型も文字列であるため、null 文字の出力は切り捨てられます。これを回避する方法は何ですか?または、文字列ではなくバッファで動作する、使用する必要がある他の暗号化ライブラリはありますか?

4

1 に答える 1

0

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");
}
于 2013-10-09T20:54:46.527 に答える