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 ?
Asked
Active
Viewed 1.1k times
6
-
Just curious... what do you need this for? If you are trying to encrypt a communication, I would suggest using a standard library that already implements SSL rather than rolling your own. – Michael Aaron Safyan Feb 18 '14 at 11:35
-
@MichaelAaronSafyan: i have to do some encryption/decryption through java class. I want the key generation to happen only once and it should be done manually using UNIX command.I will read this secret key from file in java class and perform encryption/decryption. – user3244519 Feb 18 '14 at 11:40
-
4`dd bs=1 if=/dev/random of=/home/users/cryptonoob/aes_key count=32` – President James K. Polk Feb 18 '14 at 12:24
1 Answers
5
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...

Ebbe M. Pedersen
- 7,250
- 3
- 27
- 47