title: AES Encrypt and Decrypt between C# and PHP MCrypt
body: <p>I seem to be having problems getting an AES256 string to decode between a PHP and .NET application. I get an error in the .Net application stating "Padding is invalid and cannot be removed." This error fires in the using statement for the CrytoStream. The workflow is pretty straight forward. The PHP application encrypts a value and passes it to the .NET application as a URL parameter. The .NET application needs to decrypt that value for later use. The .NET method works from .NET to .NET, but PHP to .NET is the problem. </p>
  
  <p>The PHP code:</p>
  
  <pre><code>   function encrypt($text) {
      $key = "M2AZULUALPHA";
      $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
      $padding = $block - (strlen($text) % $block);
      $text .= str_repeat(chr($padding), $padding);
  
      $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, 'TripBuilder2017');
      return base64_encode($crypttext);
   }
  </code></pre>
  
  <p>The .NET Decrypt method:</p>
  
  <pre><code>    private string Decrypt(string cipherText)
      {
          string EncryptionKey = "M2AZULUALPHA";
          byte[] saltArray = Encoding.ASCII.GetBytes("TripBuilder2017");
  
          cipherText = cipherText.Replace(" ", "+");
          byte[] cipherBytes = Convert.FromBase64String(cipherText);
          using (Aes encryptor = Aes.Create())
          {
              Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, saltArray);
              encryptor.KeySize = 256;
              encryptor.Padding = PaddingMode.PKCS7;
              encryptor.Key = pdb.GetBytes(32);
              encryptor.IV = pdb.GetBytes(16);
  
              using (MemoryStream ms = new MemoryStream())
              {
                  using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                  {
                      cs.Write(cipherBytes, 0, cipherBytes.Length);
                      cs.Close();
                  }
                  cipherText = Encoding.Unicode.GetString(ms.ToArray());
              }
          }
          return cipherText;
      }
  </code></pre>
  
  <p><strong>UPDATE</strong>
  I changed the mode in PHP to Rijndael256 and I also changed AES to RijndaelManaged in .NET. Again, I am able to get this working between .NET applications, but not with the PHP application. I am wondering if there is an issue with the padding the PHP application is using.</p>