• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Java SecretKeyFactory生成的密钥和输入密码相同

用户头像
it1352
帮助1

问题说明

我正在尝试使用PBE生成密钥,但是SecretKeyFactory生成的密钥与输入密码完全相同.我尝试了不同的算法,迭代次数等,但仍然是相同的,因此我觉得这里缺少步骤了.

I'm trying to generate a secret key using PBE but the secret key generated by the SecretKeyFactory is exactly the same as the input password. I've tried different algorithms, iteration counts etc. and it is still the same so I feel I'm missing a step here.

public SecretKey generateKey(String password, String salt) {
    char[] passChars =   password.toCharArray();
    byte[] saltBytes =   salt.getBytes();
    SecretKeyFactory keyFactory =   SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128");
    PBEKeySpec keySpec  =   new PBEKeySpec(passChars, saltBytes, 2048, 128);
    SecretKey secretKey =   keyFactory.generateSecret(keySpec);
    byte[] encodedKey =   secretKey.getEncoded();
    System.out.println("key: "   new String(encodedKey));

    return new SecretKeySpec(encodedKey, "AES"); 
}

如果我使用算法"PBKDF2WithHmacSHA1",则生成的密钥与密码不同,但是我使用的算法怎么生成与输入密码完全相同的密钥?

if I use the algorithm "PBKDF2WithHmacSHA1" then the key generated is different from the password, but how come the algorithm I'm using is generating a key that is exactly the same as the input password?

正确答案

#1

使用SecretKeyFactory PBEWithHmacSHA256AndAES_128 生成 SecretKey 时,您将获得 com的实例.sun.crypto.provider.PBEKey ,并且此类具有特殊功能",即在调用 getEncoded()而不是加密密钥时,它将返回原始的密钥"(即密码)材料.如果我对它的理解正确,那么密钥派生将不是由KeyFactory而是由密码本身进行的.

When you generate a SecretKey using the SecretKeyFactory PBEWithHmacSHA256AndAES_128 you will get an instance of com.sun.crypto.provider.PBEKey and this class has the "special feature" that it returns the original "key" (aka password) when calling getEncoded() and not the cryptographic key material. If I understand it correctly the key derivation will not be made by the KeyFactory but by the Cipher itself.

因此,您不应尝试将 SecretKey 实例转换为 SecretKeySpec 实例;而是仅在正确的密码实例中使用生成的 SecretKey 实例:

Therefore you should not try to convert the SecretKey instance into a SecretKeySpec instance; instead just use the generated SecretKey instance in the correct cipher instance:

Cipher c = Cipher.getInstance("PBEWithHmacSHA256AndAES_128");
c.init(Cipher.ENCRYPT_MODE, secretKey);

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfkakc
系列文章
更多 icon
同类精品
更多 icon
继续加载