I wanted to implement a custom secret key with AES encryption and I have found the following implementation and details about doing so.
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");
But I have the following doubts:
byte[] my_key = (SALT2 + username + my_custom_secret_key).getBytes("UTF-8");
SecretKeySpec secretKeySpec = new SecretKeySpec(my_key, "AES");
If I were to use typical sample codes like:
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
- How/where should I store my secret key i.e. "mysecretkey_123456"
- 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?
- Why can't I send the cleartext secret key as byte[] ?
- 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.