PHP JAVA 的 StandardStringDigester 的实现

PHP implementation of JAVA's StandardStringDigester

我正在尝试在 PHP 中实现 Java 的 StandardStringDigester 摘要函数以使用 SHA-1 算法摘要字符串。我没有加密方面的经验,所以我在不理解的情况下尝试了一些东西。工作 Java 示例如下:

import java.net.URLEncoder;
import org.jasypt.digest.StandardStringDigester;
import java.io.UnsupportedEncodingException;

public class Main
{

  public static void main (String[]args)
  {
    String x = "XUXoV2VYc7zYJ8UN";
    int n = 854;
    StandardStringDigester clientsd = new StandardStringDigester ();
      clientsd.setIterations (n - 1);
      clientsd.setAlgorithm ("SHA-1");
      clientsd.setSaltSizeBytes (0);    //no salt
    String clientDigest = clientsd.digest (x);
    String URLclientDigest = "a";
    try {
         URLclientDigest = URLEncoder.encode (clientDigest, "UTF-8");
    } catch(UnsupportedEncodingException ex){
                            System.out.println("Encoding not supported");
                            ex.printStackTrace();
            }
      System.out.println (URLclientDigest);
  }
}

在 PHP 我尝试了一些东西:

$n = 854;
$x = 'XUXoV2VYc7zYJ8UN';

return hash_pbkdf2('sha1', $x, null, $n);

我也用 $n -1 尝试了上面的代码。 在上面的示例中,x 是消息,n 是迭代。 我不太确定我在这里做什么。也许有一个 PHP 图书馆有人可以指点我或者任何方向将不胜感激。

根据StandardStringDigester (which is part of the Jasypt库的文档),哈希生成如下:

The steps taken for creating digests are:

  1. The String message is converted to a byte array
  2. A salt of the specified size is generated (see SaltGenerator).
  3. The salt bytes are added to the message.
  4. The hash function is applied to the salt and message altogether, and then to the results of the function itself, as many times as specified (iterations).
  5. If specified by the salt generator (see SaltGenerator.includePlainSaltInEncryptionResults()), the undigested salt and the final result of the hash function are concatenated and returned as a result.
  6. The result of the concatenation is encoded in BASE64 or HEXADECIMAL and returned as an ASCII String.

由于您的情况没有使用盐,可能的 PHP 实现是:

$n = 854;
$x = 'XUXoV2VYc7zYJ8UN';

$hash = $x;
for ($counter = 0; $counter < $n - 1; $counter++){
    $hash = hash('sha1', $hash, true);
}

print(base64_encode($hash)); // QGFgek+pfZ6nMk8Jn3stOe5KeEY=

结果 QGFgek+pfZ6nMk8Jn3stOe5KeEY= 类似于 Java 代码(在 URL 编码之前)。

注意:如果在 Java 代码中使用盐(例如 ByteArrayFixedSaltGenerator),则 PHP 代码中的盐必须与循环前的消息连接: $hash = $salt . $x;(而不是 $hash = $x;)。