PHP alternative of “PBKDF2WithHmacSHA256” from Java

你离开我真会死。 提交于 2021-01-28 05:14:28

问题


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:

  • hash_pbkdf2 - http://php.net/manual/en/function.hash-pbkdf2.php
  • hash_hmac - http://php.net/manual/en/function.hash-hmac.php

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

回答1:


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.



来源:https://stackoverflow.com/questions/46429683/php-alternative-of-pbkdf2withhmacsha256-from-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!