title: PHP mcrypt same key + base64 + urlencode = different values
body: <p>I am trying to use mcrypt to encrypt a value on one PHP site and decrypt it on another one. Sometimes it works (like 80% of the time), sometimes it doesn't work.
  Now I found out that the encrypted text is different when encrypting the same values with the same key. How is this possible?
  What am I missing?</p>
  
  <p>Here is the code for encryption:</p>
  
  <pre><code># key is always the same
  $key = "mysimplekey";
  
  # text is always the same
  $plaintext = "text_to_encrypt";
  
  $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  
  $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_CBC, $iv);
  
  $ciphertext = $iv . $ciphertext;
  
  $ciphertext_base64 = base64_encode($ciphertext);
  $ciphertext_url = rawurlencode($ciphertext_base64);
  
  # gives different values for the same key &amp; encryption text:                    
  echo $ciphertext_url;
  </code></pre>
  
  <p>Code for decryption:</p>
  
  <pre><code>$key = 'mysimplekey';
  
  $ciphertext_dec = base64_decode($_REQUEST['u']);
  $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  
  # retrieves the IV, iv_size should be created using mcrypt_get_iv_size()
  $iv_dec = substr($ciphertext_dec, 0, $iv_size);
  
  # retrieves the cipher text (everything except the $iv_size in the front)
  $ciphertext_dec = substr($ciphertext_dec, $iv_size);
  
  # may remove 00h valued characters from end of plain text
  $ciphertext_dec = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec));
  </code></pre>