[SOLVED] Rfc2898DeriveBytes.Pbkdf2 compatible with Java version

Eugen 1 Reputation point

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

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

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)


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.
9,460 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Eugen 1 Reputation point

    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