Search code examples
phpsha256hmacpbkdf2

PHP alternative of "PBKDF2WithHmacSHA256" from Java


I need to generate in PHP the same hash as as the PBKDF2WithHmacSHA256 algorithm generates in Java.

I did some research and found two functions that seem to be connected to PBKDF2 and HMAC:

What PHP functions should I use? Is it even possible with native PHP functions?

Edit #1

My Java code, the same result I need achieve in PHP

public static byte[] derivateKey(char[] password, byte[] salt, int iterations, int keyLengthBits) {
        try {
            SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
            PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, keyLengthBits);
            SecretKey key = skf.generateSecret(spec);
            byte[] res = key.getEncoded();
            return res;

        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new IllegalStateException("Could not create hash", e);
        }
    }

Solution

  • The Java code you've provided is basically hash_pbkdf2(). You just need to pass the correct params:

    function derivateKey($password, $salt, $iterations, $keyLengthBits)
    {
        return hash_pbkdf2(
            'sha256',
            $password,
            $salt,
            $iterations,
            $keyLengthBits / 8,
            true
        );
    }
    

    Obviously, PHP's hash_pbkdf2() accepts the hash algorithm as a parameter, but the potentially tricky differences are these:

    • It doesn't comply with RFC 2898 in that its length is applied after hex-encoding, so that last parameter must be set to true to make it consistent with the spec.
    • It accepts the output length in bytes instead of bits (hence why we divide by 8 above).

    The only thing I'm not sure about is what key.getEncoded() does in your sample code ... there's no encoding algorithm specified anywhere.
    I found some docs suggesting it is supposed to be RAW, so the example I'm providing should match it. If it doesn't, you'll have to encode it yourself.