Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 305
user3244519 Avatar asked Feb 18 '14 11:02

user3244519


1 Answers

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...
like image 110
Ebbe M. Pedersen Avatar answered Oct 29 '22 17:10

Ebbe M. Pedersen