如何在JAVA中编码和解码SecretKey?

如何在JAVA中编码和解码SecretKey?,java,cryptography,Java,Cryptography,上面显示的代码试图将输入编码为SecretKey并存储到keystore中。下面显示的代码是如何从keystore检索密钥的。但我不知道如何把它解码回原值 KeyStore ks = KeyStore.getInstance("JCEKS"); ks.load(null, null); SecretKey skInput = new SecretKeySpec("input".getBytes(), "DESede"); SecretKeyEntry skeInput = new KeyStor

上面显示的代码试图将
输入编码为SecretKey并存储到keystore中。下面显示的代码是如何从keystore检索密钥的。但我不知道如何把它解码回原值

KeyStore ks = KeyStore.getInstance("JCEKS");
ks.load(null, null);
SecretKey skInput = new SecretKeySpec("input".getBytes(), "DESede");
SecretKeyEntry skeInput = new KeyStore.SecretKeyEntry(skInput);
ks.setEntry("input_key", skeInput, new KeyStore.PasswordProtection("banana".toCharArray()));
FileOutputStream fos = new FileOutputStream("my.keystore");
pambks.store(fos, "password".toCharArray());
fos.flush();
fos.close();

我不确定这是否是对SecretKey进行加密和解密的正确方法,如果我错了,请纠正我。

读回这个问答,我想我误解了这个问题

通过调用键上的getEncoded方法,可以获得键的字节表示形式。之后,可以使用一个字符串构造函数将其还原为文本。如上所述,您不应该使用字符串作为键。请注意,DES键在最后一位包含奇偶校验,因此这可能会改变结果。要使用字符串作为键,建议使用十六进制。请注意,键应该具有足够的熵,而字符串不可能提供这一点


上面的代码中有几点不完全正确:

  • 你不应该(永远)使用
    “input”.getBytes()
    。首先,
    getBytes()
    使用特定于平台的默认字符编码。如果要将DES密钥用作字符串,请使用十六进制解码器对其进行解码(例如,在Apache Commons编解码器或Bouncy Castle中)

  • 您应该使用24个字节作为DESede密钥<代码>“输入”。getBytes()
  • 没有返回足够的字节

  • 对于DES密钥,只要确保设置了奇偶校验位,就需要通过
    KeyFactory
    设置密钥规范。他们会告诉你钥匙是有效的

  • 要获得大量密钥数据,请使用PBKDF2作为密码或使用随机生成的密钥

    加密密钥存储是否足以存储加密密钥取决于用例和其他安全措施

    FileInputStream fin = new FileInputStream("my.keystore");
    KeyStore ks = KeyStore.getInstance("JCEKS");
    ks.load(fin, "password".toCharArray());
    SecretKeyEntry ske = (SecretKeyEntry) readks.getEntry("input_key", new KeyStore.PasswordProtection("banana".toCharArray()));
    SecretKey sk = ske.getSecretKey();