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

Uda*_*nth 5 java cryptography secret-key

我正在编写一个在DES中进行加密和解密的程序.加密过程中使用的密钥应该在解密时使用吗?我的问题是加密和解密是在不同的机器上运行的.这是密钥在加密过程中的生成方式.

SecretKey key = KeyGenerator.getInstance("DES").generateKey();
Run Code Online (Sandbox Code Playgroud)

所以,我以为我会把密钥写入文件.但看起来我可以将一个SecretKey对象强制转换为String但反之亦然!那么,如何提取文本文件中包含的密钥呢?并作为此声明的输入传递?

 decipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
Run Code Online (Sandbox Code Playgroud)

否则是否可以在加密和解密过程中将密钥作为用户的输入?

Ras*_*ber 12

做这个:

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

然后呢:

byte[] encoded = // load it again
SecretKey key = new SecretKeySpec(encoded, "DES");
Run Code Online (Sandbox Code Playgroud)

但请记住,今天DES是不安全的(它可以相对容易地强制执行).强烈考虑使用AES代替(只需将"DES"替换为"AES").