title: SHA1 the PHP mcrypt_decrypt result
body: <p>I have 2 encrypt &amp; decrypt functions using PHP mcrypt library.</p>
  
  <pre><code>public function encrypt_string($input, $key) {
      $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
      $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
      $cipher = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $input, MCRYPT_MODE_CBC, $iv);
      return base64_encode($iv . $cipher);
  }
  public function decrypt_string($input, $key) {
      $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
      $ciphertext = base64_decode($input);
      $iv = substr($ciphertext, 0, $iv_size);
      $cipher = substr($ciphertext, $iv_size);
      return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $cipher, MCRYPT_MODE_CBC, $iv);
  }
  </code></pre>
  
  <p>Given that the key is generated by:</p>
  
  <pre><code>$key = pack('H*', 'dfgsdighsdfksdhfosdfasdjldsfsdfgdfkgdl'); // a random key
  </code></pre>
  
  <p>I can successfully obtain back the input after encryption &amp; decryption.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>$pass = '123456';
  echo sha1($pass) . PHP_EOL; // prints 7c4a8d09ca3762af61e59520943dc26494f8941b
  $pass_cipher = encrypt_string($pass, $key);
  $pass_decrypt = decrypt_string($pass_cipher, $key);
  echo $pass_decrypt . PHP_EOL; // prints 123456
  echo sha1($pass_decrypt) . PHP_EOL; // prints f41b44dbecccaccfbb4ccf6a7fc4921c03878c6d
  </code></pre>
  
  <p>However, the SHA1 result is different:</p>
  
  <pre><code>7c4a8d09ca3762af61e59520943dc26494f8941b // before encrypt &amp; decrypt
  f41b44dbecccaccfbb4ccf6a7fc4921c03878c6d // after encrypt &amp; decrypt
  </code></pre>
  
  <p>Why is it different ? What did I miss ?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>The accepted answer is useful. For people who wants additional information, here it is:</p>
  
  <pre><code>echo bin2hex($pass) . PHP_EOL; // prints 313233343536
  echo bin2hex($pass_decrypt) . PHP_EOL; // prints 31323334353600000000000000000000
  </code></pre>
  
  <p>and after <code>trim()</code>, the SHA1 result works as expected, as empty hidden <code>0</code> are removed.</p>