How to generate AES secret key and write the key to a file in UNIX How to generate AES secret key and write the key to a file in UNIX unix unix

How to generate AES secret key and write the key to a file in UNIX


An AES key is just some random bytes, of 16, 24 or 32 bytes length - depending of key size, and can in principle be stored in the file system as an binary file. However I do recommend that you put it in a Java Key Store, and protect it by password. You can use the java keytool to do all of this, like this:

keytool -genseckey -alias myKey -keyalg AES -keysize 128 -storepass passw0rd -keypass passw0rd -storetype JCEKS -keystore keystore.jks

You can then read if from java like:

KeyStore keyStore = KeyStore.getInstance("JCEKS");keyStore.load(new FileInputStream("keystore.jks"), "passw0rd".toCharArray());Key key = keyStore.getKey("myKey", "passw0rd".toCharArray());byte[] raw = key.getEncoded();SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");etc...