title: Java 256-bit AES Password-Based Encryption
body: <p>I need to implement 256 bit AES encryption, but all the examples I have found online use a "KeyGenerator" to generate a 256 bit key, but I would like to use my own passkey. How can I create my own key? I have tried padding it out to 256 bits, but then I get an error saying that the key is too long. I do have the unlimited jurisdiction patch installed, so thats not the problem :)</p>
  
  <p>Ie. The KeyGenerator looks like this ...</p>
  
  <pre><code>// Get the KeyGenerator
  KeyGenerator kgen = KeyGenerator.getInstance("AES");
  kgen.init(128); // 192 and 256 bits may not be available
  
  // Generate the secret key specs.
  SecretKey skey = kgen.generateKey();
  byte[] raw = skey.getEncoded();
  </code></pre>
  
  <p><a href="http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html" rel="noreferrer">Code taken from here</a></p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I was actually padding the password out to 256 bytes, not bits, which is too long. The following is some code I am using now that I have some more experience with this.</p>
  
  <pre><code>byte[] key = null; // TODO
  byte[] input = null; // TODO
  byte[] output = null;
  SecretKeySpec keySpec = null;
  keySpec = new SecretKeySpec(key, "AES");
  Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
  cipher.init(Cipher.ENCRYPT_MODE, keySpec);
  output = cipher.doFinal(input)
  </code></pre>
  
  <p>The "TODO" bits you need to do yourself :-)</p>