hash_update_file

hash_update_file(HashContext $context, string $filename, ?resource $stream_context = null): bool

Streams a file into a running hash context (the file version of the hash_init three-step): constant memory, the standard way to digest large files; on failure it returns false and leaves the context usable.

C C23

C23
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "sha256.h"

int main(void) {
    /* hash_init -> update(file) -> final: stream the file through the context */
    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 bytes */
    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");
    /* Chunked in-memory equivalence: 1000 x "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;
}
Output
42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a

C++ C++26

C++26
#include <cstdio>
#include <filesystem>
#include <fstream>
#include "sha256.h"

int main() {
    // hash_init -> update(file) -> final: stream the file through the context
    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 bytes
    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;
}
Output
42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a

C# v11.0.100

v11.0.100
// SHA256.ComputeHash(stream) streams the file through the hash -
// the hash_init + hash_update_file + hash_final pattern
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 fixed bytes
}
using (var stream = File.OpenRead(path))
using (var sha = System.Security.Cryptography.SHA256.Create())
{
    Console.WriteLine("streamed: " + Convert.ToHexString(sha.ComputeHash(stream)).ToLowerInvariant());
}
// Chunked in-memory equivalence with 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);
Output
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a

Go v1.27.4

v1.27.4
package main

import (
	"crypto/sha256"
	"fmt"
	"io"
	"os"
)

func main() {
	// sha256 objects implement io.Writer: io.Copy streams the file
	// straight into the hash (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 fixed bytes
	}
	f.Close()
	h := sha256.New()
	src, _ := os.Open(path)
	io.Copy(h, src)
	src.Close()
	fmt.Printf("streamed: %x\n", h.Sum(nil))
	// Chunked in-memory equivalence
	h2 := sha256.New()
	for i := 0; i < 1000; i++ {
		h2.Write([]byte("codeabc"))
	}
	fmt.Printf("chunked : %x\n", h2.Sum(nil))
	os.Remove(path)
}
Output
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a

Java v27.0.1

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 streams a file into a MessageDigest -
        // the hash_init + hash_update_file + hash_final pattern
        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 fixed bytes
            }
        }
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        try (InputStream in = Files.newInputStream(path);
             DigestInputStream dis = new DigestInputStream(in, md)) {
            dis.readAllBytes(); // stream the whole file through the digest
        }
        System.out.println("streamed: " + hex(md.digest()));
        // Chunked in-memory equivalence
        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();
    }
}
Output
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a

JavaScript v26.13.1

v26.13.1
// crypto.createHash + block reads stream the file into the hash -
// the hash_init + hash_update_file + hash_final pattern
// (CommonJS: node -e cannot run import-from-crypto code)
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 fixed bytes
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"));
// Chunked in-memory equivalence
const hash2 = createHash("sha256");
for (let i = 0; i < 1000; i++) hash2.update("codeabc");
console.log("chunked :", hash2.digest("hex"));
unlinkSync(path);
Output
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a

PHP v8.6.0

v8.6.0
// hash_update_file: stream a FILE into a running hash context
$payload = str_repeat('codeabc', 1000); // 7000 fixed bytes
$file = tempnam(sys_get_temp_dir(), 'h');
file_put_contents($file, $payload);
// Three-step pattern: init -> update (from file) -> final
$ctx = hash_init('sha256');
var_dump(hash_update_file($ctx, $file));
printf("streamed: %s\n", hash_final($ctx));
// Chunked in-memory equivalence with hash_update (see its entry)
$ctx2 = hash_init('sha256');
for ($i = 0; $i < 1000; $i++) { hash_update($ctx2, "codeabc"); }
printf("chunked : %s\n", hash_final($ctx2));
// A missing file fails without destroying the context
$ctx3 = hash_init('sha256');
var_dump(hash_update_file($ctx3, '/no/such/file'));
printf("still usable: %s\n", hash_final($ctx3));
unlink($file);
Output
bool(true)
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
bool(false)
still usable: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

Python v3.15.2

v3.15.2
import hashlib
from pathlib import Path

# hashlib.file_digest (3.11+) is the stdlib file-streaming digest -
# one call mirrors hash_init + hash_update_file + hash_final
path = Path("/tmp/a43_hash_py")
path.write_bytes(b"codeabc" * 1000)  # 7000 fixed bytes
with path.open("rb") as f:
    print("streamed:", hashlib.file_digest(f, "sha256").hexdigest())
# Chunked in-memory equivalence with hash_update
h = hashlib.sha256()
for _ in range(1000):
    h.update(b"codeabc")
print("chunked :", h.hexdigest())
path.unlink()
Output
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a

Rust v1.99.1

v1.99.1
use sha2::{Digest, Sha256};
use std::fs::File;
use std::io::Read;

fn main() {
    // Sha256 is fed in blocks: stream the file through the context -
    // the hash_init + hash_update_file + hash_final pattern
    let path = "/tmp/a43_hash_rs";
    std::fs::write(path, "codeabc".repeat(1000)).unwrap(); // 7000 fixed bytes
    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!();
    // Chunked in-memory equivalence
    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();
}
Output
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a

TypeScript v26.13.1

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 + block reads stream the file into the hash -
// the hash_init + hash_update_file + hash_final pattern
const path = join(tmpdir(), "a43_hash_ts");
writeFileSync(path, "codeabc".repeat(1000)); // 7000 fixed bytes
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"));
// Chunked in-memory equivalence
const hash2 = createHash("sha256");
for (let i = 0; i < 1000; i++) hash2.update("codeabc");
console.log("chunked :", hash2.digest("hex"));
unlinkSync(path);
Output
streamed: 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a
chunked : 42f455cd8bcd2cd58eb8230a7cd9c237b3a3c2649f7550deb897cc52246ff34a

Language differences

C: no standard hashing - the repo-vendored Brad Conte sha256 (#include "sha256.h") offers sha256_init/update/final in three steps (isomorphic to the hash_init family); file streaming is an fread loop feeding update (example).

C++: same vendored sha256 three-step; ifstream::read + gcount() handles the tail block.

C#: SHA256.ComputeHash(stream) streams in one call (block reads inside); the incremental counterpart is TransformBlock/TransformFinalBlock (the hash_update three-step).

Go: hash objects implement io.Writer - io.Copy(hash, file) is the native equivalent of the file-based hash_update_file; hash.Sum(nil) finishes.

Java: DigestInputStream wraps the stream + readAllBytes() - reading the file feeds the digest; md.digest() finishes.

JavaScript: crypto.createHash has no file variant - a readSync block loop feeds hash.update (example); or stream pipeline(readStream, hash); note the runner executes JS with node -e - importing the crypto module gets mangled by node's CJS-conversion heuristic (it wraps the code in a require-injecting form and leaves the import behind as a syntax error), so require style is safest for crypto (fs/os/path imports are unaffected).

PHP: hash_update_file($ctx, $file) is the file version of hash_update - large files need no manual chunking; on failure it returns false and the context can still be fed/finalized (the example shows hash_final returning the empty-string digest); the trio is hash_init/hash_final with hash_update (the in-memory version); hash_file is the one-shot alternative when no incrementality is needed.

Python: hashlib.file_digest(fileobj, 'sha256') (3.11+) streams natively in one call - the closest counterpart among the languages; older versions use a chunked update loop.

Rust: the sha2 crate's new/update/finalize three-step (isomorphic to the hash_init family); file streaming relies on a read block loop (example); multi-GB files stay memory-constant too.

TypeScript: same as JavaScript - createHash + block reads.