开发者

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

开发者 https://www.devze.com 2023-03-13 20:03 出处:网络
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 decrypt

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("DE开发者_StackOverflowS").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?


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消