Reputation: 421
Trying to get a java implementation of PBKDF2, I used this as my C# version: https://github.com/shawnmclean/SimpleCrypto.net
My code:
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class PBKDF2 {
public static void main(String[] args) {
try {
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec ks = new PBEKeySpec("iamtwentycharacterss".toCharArray(),"50.eGIYr3ZpxpWw67utH17s/A==".getBytes(),50,64);
SecretKey s = f.generateSecret(ks);
Key k = new SecretKeySpec(s.getEncoded(),"HmacSHA1");
System.out.println(new String(k.getEncoded()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
}
I've tried various answers on stackoverflow:
Java - PBKDF2 with HMACSHA256 as the PRF
Password Verification with PBKDF2 in Java
Unfortunately the result's don't match, the result is supposed to be:
mOs/Mw7ZRM99i/BTJ+xnmj5Pm6QlqP1vuPqrf/Qa3WwassxI1QJ447OqdoBzunbJjvrx7+bHAO1Dnj8ltS4TKA==
Upvotes: 3
Views: 2504
Reputation: 20603
How i missed this point....
The desired key length in the program is 64 but the result's key length you are expecting is 512. Change desired key length in the pbekeyspec to 512
KeySpec ks = new PBEKeySpec("iamtwentycharacterss".toCharArray(),"50.eGIYr3ZpxpWw67utH17s/A==".getBytes(),50,512);
Upvotes: 0
Reputation: 421
I have resolved my issue with the following code if it may be of assistance, Rfc2898DeriveBytes class: http://pastebin.com/iReZJ3Vq
import java.nio.charset.Charset;
import org.bouncycastle.util.encoders.Base64;
public class PBKDF2 {
public static void main(String[] args) {
try {
String password = "iamtwentycharacterss";
String salt = "50.eGIYr3ZpxpWw67utH17s/A==";
int iterations = Integer.parseInt(salt.substring(0, salt.indexOf('.')));
byte[] saltBytes = salt.getBytes(Charset.forName("UTF-8"));
Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password, saltBytes, iterations);
byte[] key = rfc2898.getBytes(64);
String hash = new String(Base64.encode(key));
System.out.println(hash);
} catch (Exception ex) {
System.out.println("ERROR: " + ex);
}
}
}
Upvotes: 2