title: AES Encryption IV's
body: <p>I am using this below (E.1) for my application, there is obviously a huge glaring security hole in this that I recognize and understand. I have grown interested in encryption and want to understand it better, I need to generate a random key along with an IV but am unsure how to do so properly Can someone explain to me whom is familiar with AES encryption how this works (IV &amp; KEY) So I am better able to understand in the future and can apply my knowledge, essentially I just want to make the code more secure, thank you.</p>
  
  <p><strong>(E.1)</strong></p>
  
  <pre><code>    byte[] key = "mykey".getBytes("UTF-8");
  
      private byte[] getKeyBytes(final byte[] key) throws Exception {
          byte[] keyBytes = new byte[16];
          System.arraycopy(key, 0, keyBytes, 0, Math.min(key.length, keyBytes.length));
          return keyBytes;
      }
  
      public Cipher getCipherEncrypt(final byte[] key) throws Exception {
          byte[] keyBytes = getKeyBytes(key);
          Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
          SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
          IvParameterSpec ivParameterSpec = new IvParameterSpec(keyBytes);
          cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
          return cipher;
      }
  
      public void encrypt(File in, File output, byte[] key) throws Exception {
  
          Cipher cipher = getCipherEncrypt(key);
          FileOutputStream fos = null;
          CipherOutputStream cos = null;
          FileInputStream fis = null;
          try {
              fis = new FileInputStream(in);
              fos = new FileOutputStream(output);
              cos = new CipherOutputStream(fos, cipher);
              byte[] data = new byte[1024];
              int read = fis.read(data);
              while (read != -1) {
                  cos.write(data, 0, read);
                  read = fis.read(data);
               System.out.println(new String(data, "UTF-8").trim());
  
              }
              cos.flush();
  
          } finally {
  
              System.out.println("performed encrypt method now closing streams:\n" + output.toString());
              cos.close();
              fos.close();
              fis.close();
  
  
          }
      }
  
  
  public void watchMeEncrypt(){
  
  encrypt(file, new File ("example.txt),key);
  </code></pre>