我一直在尝试将java密码验证复制到python,但是结果哈希是不同的。在Python中复制Java密码哈希代码(PBKDF2WithHmacSHA1)
密码:ABCD1234
密码令牌(JAVA):$ $ 31 $ 16 sWy1dDEx52vwQUCswXDYMQMzTJC39g1_nmrK384T4-W
生成的密码令牌(蟒):$ PBKDF2 $ $ 16 c1d5MWRERXg1MnZ3UVVDcw $ qPQvE4QbrnYJTmRXk0M7wlfhH5U
从Java代码中,Iteration是16,SALT应该是sWy1dDEx52vwQUCswXDYMQMzTJC39g1_nmrK384T4-w中的前16个字符,即sWy1dDEx52vwQU Cs和哈希应该是wXDYMQMzTJC39g1_nmrK384T4-W
然而,运用变量蟒蛇给了我不同的哈希结果是,qPQvE4QbrnYJTmRXk0M7wlfhH5U这是从Java的哈希值不同。
我错过了哪里?
的Java:
private static final String ALGORITHM = "PBKDF2WithHmacSHA1";
private static final int SIZE = 128;
private static final Pattern layout = Pattern.compile("\\$31\\$(\\d\\d?)\\$(.{43})");
public boolean authenticate(char[] password, String token)
{
Matcher m = layout.matcher(token);
if (!m.matches())
throw new IllegalArgumentException("Invalid token format");
int iterations = iterations(Integer.parseInt(m.group(1)));
byte[] hash = Base64.getUrlDecoder().decode(m.group(2));
byte[] salt = Arrays.copyOfRange(hash, 0, SIZE/8);
byte[] check = pbkdf2(password, salt, iterations);
int zero = 0;
for (int idx = 0; idx < check.length; ++idx)
zero |= hash[salt.length + idx]^check[idx];
return zero == 0;
}
的Python:
from passlib.hash import pbkdf2_sha1
def hasher(password):
size = 128
key0 = "abcd1234"
iter = int(password.split("$")[2])
salt0 = password.split("$")[3][0: 16]
hash = pbkdf2_sha1.using(rounds=iter, salt = salt0.encode()).hash(key0)
print(hash.split('$')[4])
return hash
原文链接Java代码:How can I hash a password in Java?