如何在Java中使用PBKDF2获得与c#相同的结果?

问题描述

我想通过PBKDF2哈希将我的c#代码转换为java,并得到相同的结果(没有真正的产品,只需测试)。

C#:

static string Pbkdf2Hashing(string password)
    {
        byte[] salt = new byte[128 / 8];
        string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
            password: password,salt: salt,prf: KeyDerivationPrf.HMACSHA1,iterationCount: 10000,numBytesRequested: 256 / 8));
        return hashed;
    }

结果:

  1. 列表项

    oudaCubzWVIMjTxaQh1KT85fn + p2KjQRdBDXpipiS8AUA =

Java:

 static String Pbkdf2Hashing(String password) throws Exception {
    byte[] salt = new byte[128 / 8];
    int iterations = 10000;
    int derivedKeyLength = 256;
    KeySpec spec = new PBEKeySpec(password.tochararray(),salt,iterations,derivedKeyLength);
    SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    byte[] result = f.generateSecret(spec).getEncoded();
    return Base64.getEncoder().encodetoString(result);
}

结果:

dxtD2eQ/4Sj5pGnPqCTiuL6jns5apO1OHkTaJC9DTzw=

解决方法

为了使Java代码获得与C#代码相同的结果,只需在Java代码中将 PBKDF2WithHmacSHA256 替换为 PBKDF2WithHmacSHA1

由于您没有将纯文本发布到示例中,因此我将纯文本用于测试

The quick brown fox jumps over the lazy dog

C#代码和固定 Java代码都返回的

mPfEIpaydCQU15ACyPW+jPh/ctqi8q74aWhO9nWz9Q0=

结果。