title: Encryption/Decryption - iphone to java - BadPaddingException: Given final block not properly padded
body: <p>My objective is to encrypt data in Iphone and decrypt it on java server.</p>
  
  <p>I am using Symmetric encryption .</p>
  
  <p>I have generated the key using KeyGenerator at the java side.</p>
  
  <p>code for generating key is as follows:</p>
  
  <p>//Java Code for key generation</p>
  
  <pre><code>File keyFile = new File("F:/key","mykey.key");
  KeyGenerator kgen = KeyGenerator.getInstance("AES");
  kgen.init(128);
  SecretKey skey = kgen.generateKey();
  byte[] enc= skey.getEncoded();
  FileUtils.writeStringToFile(keyFile ,Base64.encodeBase64String(enc),"UTF-8");   
  </code></pre>
  
  <p>Following is the java code for decryption:</p>
  
  <p>//get key from file</p>
  
  <pre><code>File file = new File("F:/key", "mykey.key");
      SecretKeySpec keySpec= null;
  try {
      byte[] keyBytes = Base64.decodeBase64(FileUtils.readFileToString(file,"UTF-8"));
       keySpec= new SecretKeySpec(keyBytes, 0, 16, "AES");
       byte[] raw = keySpec.getEncoded();
  
  } catch (Exception e) {
      e.printStackTrace();
  }
  </code></pre>
  
  <p>//Decrypt String encryptedString(from Iphone)</p>
  
  <pre><code>byte[] tempByte = Base64.decodeBase64(encryptedString);
  
  Cipher cipher = Cipher.getInstance("AES");
  cipher.init(Cipher.DECRYPT_MODE, keySpec);
  byte[] cipherData = cipher.doFinal(tempByte);
  
  String ttt = new String(cipherData ,"UTF-8");
  System.out.println(ttt);
  </code></pre>
  
  <p>And the iphone code is similar to th code given in following link:
  <a href="https://stackoverflow.com/questions/6575450/encrypting-data-with-objective-c-and-decrypt-it-with-java-problem">Encrypting data with Objective-C and decrypt it with Java Problem</a></p>
  
  <p>I am getting the following exception while decrypting in java.</p>
  
  <p>javax.crypto.BadPaddingException: Given final block not properly padded</p>
  
  <p>Please help...</p>