来自 "PBKDF2WithHmacSHA512" 的 java 散列不同于 python CRYPT(digest_alg='pbkdf2(1000,20,sha512)', salt=True)(password)[0])

java hash from "PBKDF2WithHmacSHA512" is differs from python CRYPT(digest_alg='pbkdf2(1000,20,sha512)', salt=True)(password)[0])

我有一个数据库,其中包含使用以下 python 代码散列的密码:

result = str(CRYPT(digest_alg='pbkdf2(1000,20,sha512)', salt=True)(password)[0])

(详情可参考here

对于密码='123',它生成

pbkdf2(1000,20,sha512)$b3c56f341284f4be297564f7a3be8c6e9c10b27821f8105e0a8120

我需要使用 java 验证密码。我使用以下代码:

    validatePassword("123", "pbkdf2(1000,20,sha512)$b3c56f341284f4be297564f7a3be8c6e9c10b27821f8105e0a8120");



    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();
    }

但结果如下:

80385948513c8d1826a3a5b8abc303870d41d794
54297564f7a3be8c6e9c10b27821f8105e0a8120

请帮助我做错了什么?

在 web2py 的代码中有一种 "bug"。

散列看起来像十六进制字符串,但它被发送到 hashlib。pbkdf2_hmac(openssl 方法的代理)只是十六进制字符串的字符表示。意思是你不应该使用

byte[] salt = fromHex(parts[1]);

但是

byte[] salt = parts[1].getBytes("utf-8");

此外,您需要将 KEYLENGTH 而不是盐长度传递给 PBEKeySpec 的构造函数。

更正后的部分应为:

byte[] salt = parts[1].getBytes("utf-8");
byte[] hash = fromHex(parts[2]);
PBEKeySpec spec = new PBEKeySpec(originalPassword.toCharArray(), salt, 1000, 20*8);

替换它,代码就可以工作了。花了一段时间才弄明白 ;)