How to use the key generated by KeyGenerator later?

I am writing a program that performs encryption and decryption in DES. Should the same key used during the encryption process be used with the correct decryption? My problem is that encryption and decryption are done on different machines. This is how the key is generated during the encryption process.

SecretKey key = KeyGenerator.getInstance("DES").generateKey(); 

So, I thought that I would write the key to the file. But it looks like I can give the SecretKey object to a String object, but not vice versa! So how to extract the key contained in a text file? And pass as a contribution to this statement?

  decipher.init(Cipher.DECRYPT_MODE, key, paramSpec); 

Or is it possible to take the key as input from the user during the encryption and decryption process?

+4
source share
1 answer

Do it:

 SecretKey key = KeyGenerator.getInstance("DES").generateKey(); byte[] encoded = key.getEncoded(); // save this somewhere 

Then later:

 byte[] encoded = // load it again SecretKey key = new SecretKeySpec(encoded, "DES"); 

But please remember that DES is unsafe today (it can be relatively easily rude). Think hard about using AES (just replace DES with AES).

+11
source

All Articles