php - 如何在 PHP 中同时使用多种算法对文件进行哈希处理?

标签 php file hash md5 sha1

我想使用多种算法对给定文件进行哈希处理,但现在我按顺序进行,如下所示:

return [
    hash_file('md5', $uri),
    hash_file('sha1', $uri),
    hash_file('sha256', $uri)
];

有没有办法对只打开一个流而不是 N 的文件进行哈希处理,其中 N 是我想使用的算法数量?像这样:

return hash_file(['md5', 'sha1', 'sha256'], $uri);

最佳答案

你可以打开一个文件指针然后使用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

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

关于php - 如何在 PHP 中同时使用多种算法对文件进行哈希处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49490482/

相关文章:

php - 用于问答程序的 MySql 数据库设计

c - 如何在C中的文本文件中读取由 ','分隔的数据

C snprintf 指定用户主目录

algorithm - 确定散列函数

c# - 系统字典实现说明?

php - 不执行mysqli_query()

php - AJAX JSON + PHP JSON 错误

php - Laravel 工厂 : Manual Increment of Column

java - 为什么另一部分没有打印在下一行?

Python字典的Javascript实现