[英]java hash from “PBKDF2WithHmacSHA512” is differs from python CRYPT(digest_alg='pbkdf2(1000,20,sha512)', salt=True)(password)[0])
I have a database with passwords that are hashed using the following python code: 我有一个数据库,密码使用以下python代码进行哈希处理:
result = str(CRYPT(digest_alg='pbkdf2(1000,20,sha512)', salt=True)(password)[0])
(details can be found here ) (详情可在此处找到)
for password='123' it generates 对于密码='123',它会生成
pbkdf2(1000,20,sha512)$b3c56f341284f4be$54297564f7a3be8c6e9c10b27821f8105e0a8120
I need to validate password using java. 我需要使用java验证密码。 I use the following code:
我使用以下代码:
validatePassword("123", "pbkdf2(1000,20,sha512)$b3c56f341284f4be$54297564f7a3be8c6e9c10b27821f8105e0a8120");
private static boolean validatePassword(String originalPassword, String storedPassword) throws NoSuchAlgorithmException, InvalidKeySpecException
{
String[] parts = storedPassword.split("\\$");
byte[] salt = fromHex(parts[1]);
byte[] hash = fromHex(parts[2]);
PBEKeySpec spec = new PBEKeySpec(originalPassword.toCharArray(), salt, 1000, hash.length * 8);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
byte[] testHash = skf.generateSecret(spec).getEncoded();
System.out.println(toHex(testHash));
System.out.println(toHex(hash));
return true;
}
private static byte[] fromHex(String hex) throws NoSuchAlgorithmException
{
byte[] bytes = new byte[hex.length() / 2];
for(int i = 0; i<bytes.length ;i++)
{
bytes[i] = (byte)Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
}
return bytes;
}
private static String toHex(byte[] array)
{
StringBuilder sb = new StringBuilder();
for(int i=0; i< array.length ;i++)
{
sb.append(Integer.toString((array[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
but result is the following: 但结果如下:
80385948513c8d1826a3a5b8abc303870d41d794
54297564f7a3be8c6e9c10b27821f8105e0a8120
Please help what I am doing wrong? 请帮助我做错了什么?
There is kind of a "bug" in the code around web2py. 围绕web2py的代码中存在一种“错误”。
The hash LOOKS like a hex string, but it is sent to the hashlib.pbkdf2_hmac (a proxy to openssl's method) as just the character representation of the hex string. 散列LOOKS类似于十六进制字符串,但它被发送到hashlib.pbkdf2_hmac(openssl方法的代理),仅作为十六进制字符串的字符表示。 Meaning you should not use
意思是你不应该使用
byte[] salt = fromHex(parts[1]);
but 但
byte[] salt = parts[1].getBytes("utf-8");
In addition, you need to pass the KEYLENGTH instead of the salt length into PBEKeySpec's contructor. 此外,您需要将KEYLENGTH而不是salt长度传递给PBEKeySpec的构造函数。
The corrected part should read: 更正后的部分应为:
byte[] salt = parts[1].getBytes("utf-8");
byte[] hash = fromHex(parts[2]);
PBEKeySpec spec = new PBEKeySpec(originalPassword.toCharArray(), salt, 1000, 20*8);
Replace that and the code works. 替换它和代码工作。 It took a while to find this out ;)
这需要一段时间才能找到它;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.