php openssl_pbkdf2 equivalent in java

Brian :

I have some php code to encrypt a message to webservice. Now, I want to create the equivalent java code but get stuck. Please help

--PHP Code looks like

$length = 60;
$salt =  "MySalt";
$interation = 3000;
$bytes = openssl_pbkdf2("mypasspharse", $salt, $length, $interation, "sha1");

$value1 = substr($bytes, 0, 10);
$value2 = substr($bytes, 10, 20);
$value3 = substr($bytes, 30, 30);

return array('value1' => $value1, 'value2' => $value2, 'value3' => $value3);

--

I am trying to do the same thing in java using SecretKeyFactory. My java code looks like:

SecretKeyFactory factory = SecretKeyFactory
                .getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(passphrase.toCharArray(),
                salt.getBytes("UTF-8"), interation, length);

Now I don't know how could I get the equivalent $value1, $value2, $value3 as php code. Also, Im not sure that I am doing the correct way to write the equivalent java code with the php code above. Any idea is very appreciated.

Thank you,

Zergatul :

2 below examples produces the same output:

PHP:

$length = 60;
$salt =  "MySalt";
$interation = 10;
$bytes = openssl_pbkdf2("mypasspharse", $salt, $length, $interation, "sha1");

for ($i = 0; $i < 60; $i++)
{
    echo dechex(ord($bytes[$i]));
    echo '<br>';
}

Java:

int length = 60 * 8;
String passphrase = "mypasspharse";
String salt = "MySalt";
int iteration = 10;

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(passphrase.toCharArray(), salt.getBytes("UTF-8"), iteration, length);

byte[] bytes = factory.generateSecret(spec).getEncoded();
for (int i = 0; i < 60; i++) {
    System.out.println(Integer.toHexString(bytes[i] & 0xFF));
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156798&siteId=1