Java hash from "PBKDF2WithHmacSHA512" 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:

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

      

(details can be found here )

for password = '123' it generates

pbkdf2(1000,20,sha512)$b3c56f341284f4be$54297564f7a3be8c6e9c10b27821f8105e0a8120

      

I need to check the password using java. I am using 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 the result is as follows:

80385948513c8d1826a3a5b8abc303870d41d794
54297564f7a3be8c6e9c10b27821f8105e0a8120

      

Please help, what am I doing wrong?

+3


source to share


1 answer


There is a "bug" in the code around web2py.

The LOOK hash is like a hex string, but is sent to hashlib.pbkdf2_hmac (openssl proxy method) as the only character representation of the hex string. This means that you should not use

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

      

but

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

      



Also, you need to pass KEYLENGTH instead of the salt length to the PBEKeySpec constructor.

The corrected part should look like this:

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

      

Replace this and the code works. It took a while to figure it out;)

+2


source







All Articles