Basicly, what I want to do is instead of having the key set like
new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't', 'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };
Good because that is terrible and unsafe. It's the worst secret key. Passwords are not keys and should not be used as such.
I want it to be random(but must be 16 bytes)
You want it to be secure random:
public static void main(final String ... args) throws Exception {
final SecureRandom prng = new SecureRandom();
final byte[] aes128KeyData = new byte[128 / Byte.SIZE];
prng.nextBytes(aes128KeyData);
final SecretKey aesKey = new SecretKeySpec(aes128KeyData, "AES");
System.out.println(toHex(aesKey.getEncoded()));
}
private static String toHex(final byte[] data) {
final StringBuilder sb = new StringBuilder(data.length * 2);
for (final byte b : data) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
and to have access to it(print it on the screen).
See above.
Also, is there a way to set it as a string, instead of byte type?
Well, yes, you can decode the above hexadecimal string. But in the end the AES algorithm requires a binary key, binary plaintext and will generate binary output. The SecretKey
class is little more than a wrapper around the byte array.
To do more conversions to and from strings, learn about character-encoding and encoding...