Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a key generated by KeyGenerator at a later time?

I'm writing a program which does both encryption and decryption in DES. The same key used during the encryption process should be used while decrypting too right? My problem is encryption and decryption are run on different machines. This is how the key is generated during the encryption process.

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

So ,I thought I'll write the key to a file. But looks like I can typecast a SecretKey object to a String but not vice-versa! So, how do I extract the key contained in a text file? And pass as an input to this statement?

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

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

like image 776
Uday Kanth Avatar asked Jun 19 '11 16:06

Uday Kanth


1 Answers

Do this:

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 unsecure today (it can be relatively easily bruteforced). Strongly consider using AES instead (just replace "DES" with "AES).

like image 63
Rasmus Faber Avatar answered Nov 20 '22 13:11

Rasmus Faber