I have to generate a random secret key for AES encryption/decryption and write this key to a file in UNIX.Can someone help me to learn how to do this ?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With