How can I create the same secure hash in Java and Ruby using PBKDF2

I am migrating my web application from Ruby to Java and want to allow users to log in without resetting their passwords. Here is the Ruby code that generates the hash using pbkdf2 pearls:

PBKDF2.new { |p|
  p.password = password
  p.salt = salt
  p.iterations = 10000
}.hex_string

Reading the source for the Ruby gem uses OpenSSL :: Digest.new ("sha256") as the default hash function and generates a value of 32 bytes, which is converted to a string with 64 characters using 'unpack ("H *").

So, in Java, I tried the following:

public String generatePasswordHash(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException
{
    char[] chars = password.toCharArray();
    byte[] saltBytes =salt.getBytes();

    PBEKeySpec spec = new PBEKeySpec(chars, saltBytes, 1000, 256);
    SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    byte[] hash = skf.generateSecret(spec).getEncoded();
    BigInteger bi = new BigInteger(1, hash);
    return bi.toString(16);
}

Testing both parts of the code with password = "apassword" and salt = "somesalt", I get the following results.

Ruby: 3fa1eb7544ca49b1f371eb17d24bf0010c433fa263a84aff7df446741371706b

Java: 77a7c0b1ea9760d0b1ef02e7a2633c40ccd7848ee4fa822ec71b5794e476f354

Ruby Java, , , , , .

+4
1

. 10 000 Java 1000, , , Ruby:

    PBEKeySpec spec = new PBEKeySpec(chars, saltBytes, 10000, 256);

:

, . , .

, BigInteger.toString(16), 0, , 64 . String.format():

public static String generatePasswordHash(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException
{
    char[] chars = password.toCharArray();
    byte[] saltBytes =salt.getBytes(StandardCharsets.US_ASCII);

    PBEKeySpec spec = new PBEKeySpec(chars, saltBytes, 10000, 256);
    SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    byte[] hash = skf.generateSecret(spec).getEncoded();
    BigInteger bi = new BigInteger(1, hash);
    return String.format("%064x", bi);
}

( , salt ASCII. , , Ruby).

+5

All Articles