我有一些PHP代码可以加密发送到Web服务的消息。现在,我想创建等效的Java代码,但会卡住。请帮助
-PHP代码看起来像
$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);
-
我正在尝试使用SecretKeyFactory在Java中执行相同的操作。我的Java代码如下:
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(passphrase.toCharArray(),
salt.getBytes("UTF-8"), interation, length);
现在我不知道如何获得等效的$ value1,$ value2,$ value3作为php代码。另外,我不确定我在用上面的php代码编写等效的Java代码的正确方法。任何想法都非常感谢。
谢谢
答案 0 :(得分:0)
下面的两个示例产生相同的输出:
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));
}