如何在PHP中同时使用多种算法散列文件?

Asu*_*sur 2 php hash md5 sha1 file

我想使用多种算法来散列给定文件,但现在我按顺序执行,如下所示:

return [
    hash_file('md5', $uri),
    hash_file('sha1', $uri),
    hash_file('sha256', $uri)
];
Run Code Online (Sandbox Code Playgroud)

无论如何,哈希那个文件只打开一个流而不是N,其中N是我想要使用的算法数量?像这样的东西:

return hash_file(['md5', 'sha1', 'sha256'], $uri);
Run Code Online (Sandbox Code Playgroud)

Law*_*one 6

您可以打开文件指针然后使用hash_init()hash_update()来计算文件上的哈希值,而无需多次打开文件,然后使用hash_final()来获取生成的哈希值.

<?php
function hash_file_multi($algos = [], $filename) {
    if (!is_array($algos)) {
        throw new \InvalidArgumentException('First argument must be an array');
    }

    if (!is_string($filename)) {
        throw new \InvalidArgumentException('Second argument must be a string');
    }

    if (!file_exists($filename)) {
        throw new \InvalidArgumentException('Second argument, file not found');
    }

    $result = [];
    $fp = fopen($filename, "r");
    if ($fp) {
        // ini hash contexts
        foreach ($algos as $algo) {
            $ctx[$algo] = hash_init($algo);
        }

        // calculate hash
        while (!feof($fp)) {
            $buffer = fgets($fp, 65536);
            foreach ($ctx as $key => $context) {
                hash_update($ctx[$key], $buffer);
            }
        }

        // finalise hash and store in return
        foreach ($algos as $algo) {
            $result[$algo] = hash_final($ctx[$algo]);
        }

        fclose($fp);
    } else {
        throw new \InvalidArgumentException('Could not open file for reading');
    }   
    return $result;
}

$result = hash_file_multi(['md5', 'sha1', 'sha256'], $uri);

var_dump($result['md5'] === hash_file('md5', $uri)); //true
var_dump($result['sha1'] === hash_file('sha1', $uri)); //true
var_dump($result['sha256'] === hash_file('sha256', $uri)); //true
Run Code Online (Sandbox Code Playgroud)

也发布到PHP手册:http://php.net/manual/en/function.hash-file.php#122549