hash_update_file
hash_update_file(HashContext $context, string $filename, ?resource $stream_context = null): bool
把文件内容流式喂进运行中的哈希上下文(hash_init 三段式的文件版):内存占用恒定,大文件摘要的标准姿势;失败返回 false 且不破坏上下文。
C C23
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "sha256.h"
int main(void) {
/* hash_init -> update(文件) -> final:让文件流过上下文 */
const char *path = "/tmp/a43_hash_c";
FILE *w = fopen(path, "wb");
for (int i = 0; i < 1000; i++) fwrite("codeabc", 1, 7, w); /* 7000 字节 */
fclose(w);
SHA256_CTX ctx;
sha256_init(&ctx);
FILE *f = fopen(path, "rb");
BYTE buf[4096];
size_t n;
while ((n = fread(buf, 1, sizeof(buf), f)) > 0) sha256_update(&ctx, buf, n);
fclose(f);
BYTE digest[SHA256_BLOCK_SIZE];
sha256_final(&ctx, digest);
for (int i = 0; i < SHA256_BLOCK_SIZE; i++) printf("%02x", digest[i]);
printf("\n");
/* 分块内存等价:1000 次 "codeabc" */
SHA256_CTX ctx2;
sha256_init(&ctx2);
for (int i = 0; i < 1000; i++) sha256_update(&ctx2, (const BYTE *)"codeabc", 7);
sha256_final(&ctx2, digest);
for (int i = 0; i < SHA256_BLOCK_SIZE; i++) printf("%02x", digest[i]);
printf("\n");
unlink(path);
return 0;
}
42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
C++ C++26
#include <cstdio>
#include <filesystem>
#include <fstream>
#include "sha256.h"
int main() {
// hash_init -> update(文件) -> final:让文件流过上下文
const char *path = "/tmp/a43_hash_cpp";
std::ofstream w(path, std::ios::binary);
for (int i = 0; i < 1000; i++) w.write("codeabc", 7); // 7000 字节
w.close();
SHA256_CTX ctx;
sha256_init(&ctx);
std::ifstream f(path, std::ios::binary);
BYTE buf[4096];
while (f.read(reinterpret_cast<char *>(buf), sizeof(buf)) || f.gcount() > 0) {
sha256_update(&ctx, buf, static_cast<size_t>(f.gcount()));
if (!f) break;
}
f.close();
BYTE digest[SHA256_BLOCK_SIZE];
sha256_final(&ctx, digest);
for (int i = 0; i < SHA256_BLOCK_SIZE; i++) std::printf("%02x", digest[i]);
std::printf("\n");
std::filesystem::remove(path);
return 0;
}
42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
C# v11.0.100
// SHA256.ComputeHash(stream) 让文件流过哈希——
// hash_init + hash_update_file + hash_final 的模式
var path = Path.Combine(Path.GetTempPath(), "a43_hash_cs");
using (var w = File.Create(path))
using (var tw = new StreamWriter(w))
{
for (int i = 0; i < 1000; i++) tw.Write("codeabc"); // 固定 7000 字节
}
using (var stream = File.OpenRead(path))
using (var sha = System.Security.Cryptography.SHA256.Create())
{
Console.WriteLine("streamed: " + Convert.ToHexString(sha.ComputeHash(stream)).ToLowerInvariant());
}
// 用 TransformBlock 做分块内存等价
using var sha2 = System.Security.Cryptography.SHA256.Create();
byte[] chunk = System.Text.Encoding.ASCII.GetBytes("codeabc");
for (int i = 0; i < 1000; i++) sha2.TransformBlock(chunk, 0, chunk.Length, null, 0);
sha2.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
Console.WriteLine("chunked : " + Convert.ToHexString(sha2.Hash).ToLowerInvariant());
File.Delete(path);
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
Go v1.27.4
package main
import (
"crypto/sha256"
"fmt"
"io"
"os"
)
func main() {
// sha256 对象实现了 io.Writer:io.Copy 把文件直接流进哈希
// (hash_init + hash_update_file + hash_final 的模式)
path := "/tmp/a43_hash_go"
f, _ := os.Create(path)
for i := 0; i < 1000; i++ {
f.WriteString("codeabc") // 固定 7000 字节
}
f.Close()
h := sha256.New()
src, _ := os.Open(path)
io.Copy(h, src)
src.Close()
fmt.Printf("streamed: %x\n", h.Sum(nil))
// 分块内存等价
h2 := sha256.New()
for i := 0; i < 1000; i++ {
h2.Write([]byte("codeabc"))
}
fmt.Printf("chunked : %x\n", h2.Sum(nil))
os.Remove(path)
}
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
Java v27.0.1
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class Main {
public static void main(String[] args) throws Exception {
// DigestInputStream 把文件流进 MessageDigest——
// hash_init + hash_update_file + hash_final 的模式
Path path = Files.createTempFile("a43_hash_java", ".bin");
try (var out = Files.newOutputStream(path, StandardOpenOption.TRUNCATE_EXISTING)) {
for (int i = 0; i < 1000; i++) {
out.write("codeabc".getBytes()); // 固定 7000 字节
}
}
MessageDigest md = MessageDigest.getInstance("SHA-256");
try (InputStream in = Files.newInputStream(path);
DigestInputStream dis = new DigestInputStream(in, md)) {
dis.readAllBytes(); // 整个文件流过摘要器
}
System.out.println("streamed: " + hex(md.digest()));
// 分块内存等价
MessageDigest md2 = MessageDigest.getInstance("SHA-256");
for (int i = 0; i < 1000; i++) {
md2.update("codeabc".getBytes());
}
System.out.println("chunked : " + hex(md2.digest()));
Files.delete(path);
}
private static String hex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) sb.append(String.format("%02x", b));
return sb.toString();
}
}
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
JavaScript v26.13.1
// crypto.createHash + 分块读把文件流进哈希——
// hash_init + hash_update_file + hash_final 的模式
// (CommonJS:node -e 跑不了 import crypto 的代码)
const { createHash } = require("node:crypto");
const { writeFileSync, openSync, readSync, closeSync, unlinkSync } = require("node:fs");
const { tmpdir } = require("node:os");
const { join } = require("node:path");
const path = join(tmpdir(), "a43_hash_js");
writeFileSync(path, "codeabc".repeat(1000)); // 固定 7000 字节
const hash = createHash("sha256");
const fd = openSync(path, "r");
const buf = Buffer.alloc(4096);
let n;
while ((n = readSync(fd, buf)) > 0) hash.update(buf.subarray(0, n));
closeSync(fd);
console.log("streamed:", hash.digest("hex"));
// 分块内存等价
const hash2 = createHash("sha256");
for (let i = 0; i < 1000; i++) hash2.update("codeabc");
console.log("chunked :", hash2.digest("hex"));
unlinkSync(path);
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
PHP v8.6.0
// hash_update_file:把文件流式喂进运行中的哈希上下文
$payload = str_repeat('codeabc', 1000); // 固定 7000 字节
$file = tempnam(sys_get_temp_dir(), 'h');
file_put_contents($file, $payload);
// 三段式:init -> update(来自文件)-> final
$ctx = hash_init('sha256');
var_dump(hash_update_file($ctx, $file));
printf("streamed: %s\n", hash_final($ctx));
// 与 hash_update 的分块内存等价(详见其条目)
$ctx2 = hash_init('sha256');
for ($i = 0; $i < 1000; $i++) { hash_update($ctx2, "codeabc"); }
printf("chunked : %s\n", hash_final($ctx2));
// 文件不存在时失败且不破坏上下文
$ctx3 = hash_init('sha256');
var_dump(hash_update_file($ctx3, '/no/such/file'));
printf("still usable: %s\n", hash_final($ctx3));
unlink($file);
bool(true) streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a bool(false) still usable: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Python v3.15.2
import hashlib
from pathlib import Path
# hashlib.file_digest(3.11+)是标准库的文件流式摘要——
# 一次调用对应 hash_init + hash_update_file + hash_final
path = Path("/tmp/a43_hash_py")
path.write_bytes(b"codeabc" * 1000) # 固定 7000 字节
with path.open("rb") as f:
print("streamed:", hashlib.file_digest(f, "sha256").hexdigest())
# 与 hash_update 的分块内存等价
h = hashlib.sha256()
for _ in range(1000):
h.update(b"codeabc")
print("chunked :", h.hexdigest())
path.unlink()
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
Rust v1.99.1
use sha2::{Digest, Sha256};
use std::fs::File;
use std::io::Read;
fn main() {
// Sha256 按块喂入:让文件流过上下文——
// hash_init + hash_update_file + hash_final 的模式
let path = "/tmp/a43_hash_rs";
std::fs::write(path, "codeabc".repeat(1000)).unwrap(); // 固定 7000 字节
let mut hasher = Sha256::new();
let mut f = File::open(path).unwrap();
let mut buf = [0u8; 4096];
loop {
let n = f.read(&mut buf).unwrap();
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
print!("streamed: ");
for b in hasher.finalize() {
print!("{:02x}", b);
}
println!();
// 分块内存等价
let mut h2 = Sha256::new();
for _ in 0..1000 {
h2.update(b"codeabc");
}
print!("chunked : ");
for b in h2.finalize() {
print!("{:02x}", b);
}
println!();
std::fs::remove_file(path).unwrap();
}
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
TypeScript v26.13.1
import { createHash } from "node:crypto";
import { writeFileSync, openSync, readSync, closeSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
// crypto.createHash + 分块读把文件流进哈希——
// hash_init + hash_update_file + hash_final 的模式
const path = join(tmpdir(), "a43_hash_ts");
writeFileSync(path, "codeabc".repeat(1000)); // 固定 7000 字节
const hash = createHash("sha256");
const fd = openSync(path, "r");
const buf = Buffer.alloc(4096);
let n;
while ((n = readSync(fd, buf)) > 0) hash.update(buf.subarray(0, n));
closeSync(fd);
console.log("streamed:", hash.digest("hex"));
// 分块内存等价
const hash2 = createHash("sha256");
for (let i = 0; i < 1000; i++) hash2.update("codeabc");
console.log("chunked :", hash2.digest("hex"));
unlinkSync(path);
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
语言差异说明
C:无标准哈希——本仓库 vendor 的 Brad Conte sha256(#include "sha256.h")提供 sha256_init/update/final 三段式(与 hash_init 族同构);文件流式就是 fread 循环喂 update(示例)。
C++:同 vendor sha256 三段式;ifstream::read + gcount() 处理尾块。
C#:SHA256.ComputeHash(stream) 一步流式(内部按块读);增量等价物是 TransformBlock/TransformFinalBlock(对应 hash_update 三段式)。
Go:哈希对象实现 io.Writer——io.Copy(hash, file) 即文件版 hash_update_file 的原生等价物;hash.Sum(nil) 收尾。
Java:DigestInputStream 包装流 + readAllBytes()——读文件即喂摘要器;md.digest() 收尾。
JavaScript:crypto.createHash 没有文件版——readSync 分块循环喂 hash.update(示例);或流式 pipeline(readStream, hash);注意校验器用 node -e 跑 JS——import crypto 模块会被 node 的 CJS 转换启发式搞坏(包装成注入 require 的形式、残留 import 报语法错),crypto 侧用 require 风格最稳(fs/os/path 的 import 不受影响)。
PHP:hash_update_file($ctx, $file) 是 hash_update 的文件版——大文件场景免手动分块;失败返回 false 且上下文仍可继续喂/收尾(示例演示失败后 hash_final 返回空串摘要);配套 hash_init/hash_final 与 hash_update(内存版)三件套;另有 hash_file 一步式(不需要增量时用它)。
Python:hashlib.file_digest(fileobj, 'sha256')(3.11+)原生一步流式——各语言里最贴合的对应物;旧版本用分块 update 循环。
Rust:sha2 crate 的 new/update/finalize 三段式(与 hash_init 族同构);文件流式靠 read 分块循环(示例);2.5GB+ 大文件同样内存恒定。
TypeScript:同 JavaScript——createHash + 分块读。