title: Curious behavior by C# to Java encryption/decryption using AES
body: <p>I have very curious problem by string decryption using the AES algorithm. My C# application sends encrypted data (strings) to the Java application. Even I use the same key string, the decryption leads into the Exception:</p>
  
  <p>javax.crypto.BadPaddingException: Given final block not properly padded
      at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:810)</p>
  
  <p>however only when length of the plain input text to encrypt (at C# side) exceeds 1393 characters... But if the length equals to 1393 characters, or is lesser than  1393 characters, it works fine.</p>
  
  <p>Here is the C# codefor encryption:</p>
  
  <pre><code>    private static string Encrypt(string textToEncrypt, string key)
      {
          try
          {
              RijndaelManaged rijndaelCipher = new RijndaelManaged();
              rijndaelCipher.Mode = CipherMode.CBC;
              rijndaelCipher.Padding = PaddingMode.PKCS7;
  
              rijndaelCipher.KeySize = 0x80; // 256bit key
              rijndaelCipher.BlockSize = 0x80;
              byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
              byte[] keyBytes = new byte[0x10];
              int len = pwdBytes.Length;
              if (len &gt; keyBytes.Length)
              {
                  len = keyBytes.Length;
              }
              Array.Copy(pwdBytes, keyBytes, len);
              rijndaelCipher.Key = keyBytes;
              rijndaelCipher.IV = keyBytes;
              ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
              byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
              return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length));
          }
          catch (Exception ex)
          {
              throw ex;
          }
      }
  </code></pre>
  
  <p>And a Java code for decryption:</p>
  
  <pre><code>public static String Decrypt(String text, String key) throws Exception {
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      byte[] keyBytes = new byte[16];
      byte[] b = key.getBytes("UTF-8");
      int len = b.length;
      if (len &gt; keyBytes.length) {
          len = keyBytes.length;
      }
      System.arraycopy(b, 0, keyBytes, 0, len);
  
      SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
      IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
      cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
  
      BASE64Decoder decoder = new BASE64Decoder();
      byte[] results = cipher.doFinal(decoder.decodeBuffer(text));
      return new String(results, "UTF-8");
  }
  </code></pre>
  
  <p>I've tried replace the BASE64Decoder to Base64 codec from apache, but the result was the same...
  I will be grateful for any advice or idea. Thanks.</p>