"PBKDF2WithHmacSHA256"的PHP替代方案;来自Java [英] PHP alternative of "PBKDF2WithHmacSHA256" from Java

查看:97
本文介绍了"PBKDF2WithHmacSHA256"的PHP替代方案;来自Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在PHP中生成与Java中生成的 PBKDF2WithHmacSHA256 算法相同的哈希值.

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

我做了一些研究,发现似乎与 PBKDF2 HMAC 相关的两个函数:

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

我应该使用哪些PHP函数?原生PHP函数甚至有可能吗?

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

编辑#1

我的Java代码,需要在PHP中实现的相同结果

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

推荐答案

您提供的Java代码基本上是 hash_pbkdf2() .您只需要传递正确的参数即可:

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

很明显,PHP的 hash_pbkdf2()接受哈希算法作为参数,但是潜在的棘手区别是:

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

  • 它不符合 RFC 2898 ,因为它的长度是十六进制编码,因此必须将最后一个参数设置为 true ,以使其与规范一致.
  • 它接受以字节为单位而不是位的输出长度(因此,我们为什么要在上面除以8).
  • 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).

我唯一不确定的是示例代码中 key.getEncoded()的作用……在任何地方都没有指定编码算法.
我发现一些文档建议它应该是RAW,因此我提供的示例应该与之匹配.如果没有,则必须自己进行编码.

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.

这篇关于"PBKDF2WithHmacSHA256"的PHP替代方案;来自Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆