简体   繁体   English

如何在以后使用KeyGenerator生成的密钥?

[英]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. 我正在编写一个在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! 但看起来我可以将一个SecretKey对象强制转换为String但反之亦然! 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). 但请记住,今天DES是不安全的(它可以相对容易地强制执行)。 Strongly consider using AES instead (just replace "DES" with "AES). 强烈考虑使用AES代替(只需将“DES”替换为“AES”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM