Java Rfc2898DeriveBytes

I was creating Java port for one program of mine and I stumbled across little issue. Although C# and Java seem quite different, you can almost always rely on one-for-one feature compatibility. Of course I stumbled across one class that was not implemented in Java. That class was Rfc2898DeriveBytes (.NET PBKDF2 implementation).

To be totally correct, I did found quite a few classes that do implement RFC 2898 but they did not give same result as one I used in .NET. While those implementations were also correct ones, they did not ensure compatibility with my existing code.

.NET Reflector comes here as great debugging tool. Quick peek just discovered that core of .NET Rfc2898DeriveBytes class is HMAC SHA-1 algorithm. GetBytes method has some basic buffer management (data gets generated 20 bytes at time) and call to omnipotent Func method. It is in this method that real crypto-magic happens.

Fortunately, building blocks for this functionality is available to Java. Although syntax is somewhat different, general idea is same. Whole getBytes method needed only changes related to array copying. In .NET we would use Buffer.BlockCopy and in Java this translates perfectly to System.arraycopy. Really hard…

Crypto-core is hidden in function named “func”. Notable spot here is incrementing block counter. In C# this is unsigned int but in Java there is no such thing. That is reason for one extra check.

if (this._block == 2147483647) {
    this._block = -2147483648;
} else {
    this._block += 1;
}

With these few changes done our Java implementation of Rfc2898DeriveBytes was done. Source code can be downloaded here.