title: Cipher: What is the reason for IllegalBlockSizeException?
body: <p>I have observed the following when I worked with <a href="http://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html#doFinal%28byte%5b%5d%29" rel="noreferrer">Cipher</a>. </p>
  
  <p>Encryption code:</p>
  
  <pre><code>Cipher aes = Cipher.getInstance("AES");
  aes.init(Cipher.ENCRYPT_MODE, generateKey());
  byte[] ciphertext = aes.doFinal(rawPassword.getBytes());
  </code></pre>
  
  <p>Decryption code :</p>
  
  <pre><code>Cipher aes = Cipher.getInstance("AES");
  aes.init(Cipher.DECRYPT_MODE, generateKey());
  byte[] ciphertext = aes.doFinal(rawPassword.getBytes());
  </code></pre>
  
  <p>I get IllegalBlockSizeException ( Input length must be multiple of 16 when ...) on running the Decrypt code.</p>
  
  <p>But If I change the decrypt code to </p>
  
  <pre><code>Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding"); //I am passing the padding too
  aes.init(Cipher.DECRYPT_MODE, generateKey());
  byte[] ciphertext = aes.doFinal(rawPassword.getBytes());
  </code></pre>
  
  <p>It works fine. 
  I understand that it is in the pattern <code>algorithm/mode/padding</code>. So I thought it is because I didn't mention the padding. So I tried giving mode and padding during encryption, </p>
  
  <p>Encryption code:</p>
  
  <pre><code>Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");//Gave padding during encryption too
  aes.init(Cipher.ENCRYPT_MODE, generateKey());
  byte[] ciphertext = aes.doFinal(rawPassword.getBytes());
  </code></pre>
  
  <p>Decryption code :</p>
  
  <pre><code>Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
  aes.init(Cipher.DECRYPT_MODE, generateKey());
  byte[] ciphertext = aes.doFinal(rawPassword.getBytes());
  </code></pre>
  
  <p>But it fails with IllegalBlockSizeException.</p>
  
  <p>What is the reason, why the exception and what is exactly happening underneath. 
  If anyone can help? Thanks in advance</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Looks like the issue is with the string I am encrypting and decrypting. Because, even the code that I said works, doesn't always work. I am basically encrypting UUIDs (eg : 8e7307a2-ef01-4d7d-b854-e81ce152bbf6). It works with certain strings and doesn't with certain others.</p>
  
  <p>The length of encrypted String is 64 which is divisible by 16. Yes, I am running it on the same machine.</p>
  
  <p>Method for secret key generation:</p>
  
  <pre><code>    private Key generateKey() throws NoSuchAlgorithmException {
      MessageDigest digest = MessageDigest.getInstance("SHA");
              String passphrase = "blahbl blahbla blah";
      digest.update(passphrase.getBytes());
      return new SecretKeySpec(digest.digest(), 0, 16, "AES");
  }
  </code></pre>