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);
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfkakc
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20