Java SecretKeyFactory生成的密钥与输入密码相同 [英] Java SecretKeyFactory generated key is same as input password

查看:88
本文介绍了Java SecretKeyFactory生成的密钥与输入密码相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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?

推荐答案

使用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);

这篇关于Java SecretKeyFactory生成的密钥与输入密码相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆