title: AES 256 bit encryption - java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long
body: <p>Below is my encryption logic. Although my IV is 16bytes long, I still get an error with invalid IV length. Would appreciate any help </p>
  
  <pre><code>@Override
  public String encrypt(String dataToEncrypt, String IV) throws Exception{
      if(encryptionKey.length() &lt; 10){
          encryptionKey = generateEncryptionKey().toString();
      }
      System.out.println("number of IV bytes is "+IV.length()+" "+IV);
      Cipher cipher = Cipher.getInstance(encrpytionAlgo);
      SecretKey key = new SecretKeySpec(encryptionKey.getBytes(Charset.forName("UTF-8")), "AES");
      cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes(Charset.forName("UTF-8"))));
      byte[] encryptedTextBytes = cipher.doFinal(dataToEncrypt.getBytes(Charset.forName("UTF-8")));
      return new Base64().encodeAsString(encryptedTextBytes);
  }
  </code></pre>
  
  <p>IV and Key generation logic</p>
  
  <pre><code> @Override
  public String generateRandomIV(){
          Random random = new SecureRandom();
          byte[] iv = new byte[16];
          random.nextBytes(iv);
          System.out.println("IV is "+Base64.encodeBase64(iv)+" "+ com.sun.jersey.core.util.Base64.base64Decode(new String(Base64.encodeBase64(iv)))+ " number of bytes is "+iv.length);
          return new String(Base64.encodeBase64(iv));
  }
  
  @Override
  public SecretKey generateEncryptionKey(){
      KeyGenerator aesKey = null;
      try {
          aesKey = KeyGenerator.getInstance("AES");
      } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
      }
      aesKey.init(256);
      SecretKey secretKey = aesKey.generateKey();
      System.out.println("Encryption key is "+ new Base64().encode(secretKey.getEncoded()));
      return secretKey;
  }
  </code></pre>
  
  <p>Below is the stacktrace for the exception
  Exception is at line :<br>
  cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes(Charset.forName("UTF-8"))));</p>
  
  <pre><code>java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long
  at com.sun.crypto.provider.SunJCE_f.a(DashoA13*..)
  at com.sun.crypto.provider.AESCipher.engineInit(DashoA13*..)
  at javax.crypto.Cipher.a(DashoA13*..)
  at javax.crypto.Cipher.a(DashoA13*..)
  at javax.crypto.Cipher.init(DashoA13*..)
  at javax.crypto.Cipher.init(DashoA13*..)
  at com.intuit.platform.publiccloudaccess.core.services.EncryptionServiceImpl.encrypt(EncryptionServiceImpl.java:47)
  </code></pre>