Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of C#'s Rfc2898DerivedBytes

I was wondering if anyone have tried to do an equivalent of

Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(secret, saltValueBytes);
byte[] secretKey = key.GetBytes(16);

in Java. Where secret is a string(password), and saltValueBytes is, well, a salt in byte array.

I've tried stuff, but can't seem to wrap my head around it.

like image 477
El Che Avatar asked Jun 18 '09 12:06

El Che


2 Answers

I found this implementation by means of a Google search but I have never used it.

A free Java implementation of RFC 2898 / PKCS#5 PBKDF2

There seems to be no small and freely available Java implementation of RFC 2898 / PKCS#5 available. Small as in only a few source files, with trivial compile and no dependencies, free as in LGPL.

Given the availability of HMacSHA1 in the standard SUN JCE cryptographic provider, such an implementation is quite simple and can be derived from the RFC description quite literally. My code is a clean-room implementation with only the RFC as its basis.

like image 62
Andrew Hare Avatar answered Oct 19 '22 10:10

Andrew Hare


I know this is late to the game, but Java 6 and up does have a built-in PBKDF2 implementation.

int dkLen = 64;
int rounds = 1000;
PBEKeySpec keySpec = new PBEKeySpec("Some password".toCharArray(), "SomeSalt".getBytes(), rounds, dkLen * 8);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] out = factory.generateSecret(keySpec).getEncoded();

The list of Java 6 Security Enhancements claims comparability with PKCS#5, and through my own (cursory) testing it does appear to produce correct PBKDF2 keys.

like image 35
Syon Avatar answered Oct 19 '22 10:10

Syon