[SOLVED] Rfc2898DeriveBytes.Pbkdf2 compatible with Java version

Eugen 1 Reputation point
2023-11-09T09:35:28.82+00:00

I am trying to migrate some code that hashes passwords from C# to java and I have stumbled on an issue.

I believe I wrote the right code in Java to hash passwords using Pbkdf2 however the results are different from the ones I get using the C# code.

In C# the code lookis like this:

var pass2 = Rfc2898DeriveBytes.Pbkdf2(bytes,saltBytes,5000,HashAlgorithmName.SHA1,24);
Console.WriteLine(Convert.ToBase64String(pass2)); 

In Java, the code looks like this:

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec pbeKeySpec = new PBEKeySpec(passwordCharArray, saltBytes, 5000, 192);
Key secretKey = factory.generateSecret(pbeKeySpec);
byte[] keyBytes = secretKey.getEncoded();
Base64.getEncoder().encodeToString(keyBytes);

However, for the same input I get different results.
We are using UTF8 encoding in both languages.

I have asked this on SO with the full C# code and some example results.

I have tried multiple Java implementations and I get identical hashes, but they are different from the ones I get in C# where I tried also Zetetic.Security.Pbkdf2Hash implementation (that the original C# code I am trying to port is using)

https://stackoverflow.com/questions/77451714/working-rfc2898derivebytes-pbkdf2-in-java#273054

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,858 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Eugen 1 Reputation point
    2023-11-09T10:40:21.29+00:00

    I got a reply on SO and some sample code that helped me.

    The issue is related to encodings + some internal Java JCE issue.

    The solution is to use bouncycastle.

    The encodings differ: In the C# code the salt is Base64 decoded, in the Java code it is UTF-8 encoded. In the C# code the password is Unicode encoded specifying UTF16-LE in .NET, in the Java code it is UTF-8 encoded.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.