title: Error RijndaelManaged, "Padding is invalid and cannot be removed"
body: <p>I have error from <code>CryptoStream</code>:</p>
  <blockquote>
  <p>Padding is invalid and cannot be removed.</p>
  </blockquote>
  <h3>Code</h3>
  <pre><code>public MemoryStream EncrypteBytes(Stream inputStream, string passPhrase, string saltValue)
  {
      RijndaelManaged RijndaelCipher = new RijndaelManaged();
      RijndaelCipher.Padding = PaddingMode.PKCS7;
      RijndaelCipher.Mode = CipherMode.CBC;
      byte[] salt = Encoding.ASCII.GetBytes(saltValue);
      PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, &quot;SHA1&quot;, 2);
  
      ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(password.GetBytes(32), password.GetBytes(16));
      MemoryStream memoryStream = new MemoryStream();
      CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
      var buffer = new byte[1024];
      var read = inputStream.Read(buffer, 0, buffer.Length);
      while (read &gt; 0)
      {
          cryptoStream.Write(buffer, 0, read);
          read = inputStream.Read(buffer, 0, buffer.Length);
      }
  
      cryptoStream.FlushFinalBlock();
      memoryStream.Position = 0;
      return memoryStream;
  }
  
  // Example usage: DecryptBytes(encryptedBytes, &quot;SensitivePhrase&quot;, &quot;SodiumChloride&quot;);
  public byte[] DecrypteBytes(MemoryStream memoryStream, string passPhrase, string saltValue)
  {
      RijndaelManaged RijndaelCipher = new RijndaelManaged();
      RijndaelCipher.Padding = PaddingMode.PKCS7;
  
      RijndaelCipher.Mode = CipherMode.CBC;
      byte[] salt = Encoding.ASCII.GetBytes(saltValue);
      PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, &quot;SHA1&quot;, 2);
  
      ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(password.GetBytes(32), password.GetBytes(16));
  
  
      CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
      byte[] plainBytes = new byte[memoryStream.Length];
  
      int DecryptedCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);
  
      return plainBytes;
  }
  </code></pre>