title: How to perform AES encryption with custom secret key stored in keystore?
body: <p>I wanted to implement a custom secret key with AES encryption and I have found the following implementation and details about doing so.</p>
  
  <pre><code>byte[] key = (SALT2 + username + my_custom_secret_key).getBytes("UTF-8");
  MessageDigest sha = MessageDigest.getInstance("SHA-1");
  key = sha.digest(key);
  key = Arrays.copyOf(key, 16); // use only first 128 bit
  
  SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
  </code></pre>
  
  <p>But I have the following doubts:</p>
  
  <pre><code>byte[] my_key = (SALT2 + username + my_custom_secret_key).getBytes("UTF-8");
  SecretKeySpec secretKeySpec = new SecretKeySpec(my_key, "AES");
  </code></pre>
  
  <p>If I were to use typical sample codes like:</p>
  
  <pre><code>KeyGenerator keyGen = KeyGenerator.getInstance("AES");
  keyGen.init(128);
  SecretKey secretKey = keyGen.generateKey();
  </code></pre>
  
  <ol>
  <li>How/where should I store my secret key i.e. "mysecretkey_123456"</li>
  <li>Why is there a need to "hash" the combination of "(SALT2 + username + password)" using SHA-1/2 and pass the byte[] array to the SecretKeySpec? </li>
  <li>Why can't I send the cleartext secret key as byte[] ?</li>
  <li>I am trying to ensure the "key" is dynamic so that it is based on a salt+username+my_custom_secret_key, so that the same encrypted string will have different output.</li>
  </ol>
  
  <p><a href="https://stackoverflow.com/questions/3451670/java-aes-and-using-my-own-key">Java AES and using my own Key</a> </p>
  
  <p><a href="https://www.securecoding.cert.org/confluence/display/java/MSC61-J.+Do+not+use+insecure+or+weak+cryptographic+algorithms" rel="nofollow noreferrer">https://www.securecoding.cert.org/confluence/display/java/MSC61-J.+Do+not+use+insecure+or+weak+cryptographic+algorithms</a> </p>
  
  <p><a href="https://stackoverflow.com/questions/18268502/how-to-generate-salt-value-in-java">How to generate SALT value in Java?</a></p>