将SecretKey转换为字节,如何将其转换回SecretKey?


问题内容

我使用以下代码将密钥转换为字节

SecretKey key = KeyGenerator.getInstance("DES").generateKey();
byte[] bkey=key.getEncoded();

现在如何从中获取密钥bkey?我试过了:

SecretKeySpec secretkey = new SecretKeySpec(bkey,"DES");   
SecretKeyFactory sfkey = SecretKeyFactory.getInstance("DES");
SecretKey skey = sfkey.generateSecret(secretkey);

我收到以下错误:

Error during Exception java.security.spec.InvalidKeySpecException: Inappropriate key specification

问题答案:

这应该工作

    SecretKey key = KeyGenerator.getInstance("DES").generateKey();
    byte[] data = key.getEncoded();
    SecretKey key2 = new SecretKeySpec(data, 0, data.length, "DES");