title: Java AES - message digest for the key
body: <p>I recently searched for Java code to encrypt data with AES and found this piece of code on the net:</p>
  
  <pre><code>        MessageDigest digest = MessageDigest.getInstance("SHA-256");
          digest.update(getSecretKey().getBytes("UTF-8"));
          byte[] keyBytes = new byte[16];
          System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);
          Key aesKey = new SecretKeySpec(keyBytes, "AES");
  
          // Then encrypt
          byte[] iv = initIV();
          Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
          cipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(iv));
          byte[] encrypted = cipher.doFinal(value.getBytes(encoding));
  </code></pre>
  
  <p>I'd like to understand why the developer used a MessageDigest with the secret key. What are the benefits of such an approach, instead of writing:</p>
  
  <pre><code>        Key aesKey = new SecretKeySpec(getSecretKey().getBytes("UTF-8"), "AES");
  
          // Then encrypt
          byte[] iv = initIV();
          Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
          cipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(iv));
          byte[] encrypted = cipher.doFinal(value.getBytes(encoding));
  </code></pre>
  
  <p>Many thanks in advance</p>
  
  <p>Gilles</p>