Programming Search⌘K

Taskcore

Compute a SHA-256 hash

Also called sha256 of a string, sha256 of a file, sha256 hex digest, hash a file, checksum a file with sha256.

Compute the SHA-256 digest of the UTF-8 bytes of a string, or of the bytes of a file read in chunks, and give it as 64 lowercase hexadecimal digits.

Task

Compute the SHA-256 digest of a message, and give it as 64 lowercase hexadecimal digits.

SHA-256 is one of the hash algorithms of FIPS 180-4. It takes a message of fewer than 2^64 bits and gives a digest of 256 bits, which is 32 bytes. The standard says that it is computationally infeasible to find a message for a given digest, or two messages with the same digest. So a digest can identify a file or a message, for example to check a download.

SHA-256 works on bytes, not on characters. A string must first become bytes, and different encodings give different bytes. This task uses UTF-8 with no byte order mark and no Unicode normalization. See UTF-8.

Each solution has two functions:

  • sha256_text(text) returns the digest of the UTF-8 bytes of the string. This is the entry of the contract.
  • sha256_file(path) returns the digest of the bytes of a file. It reads the file in chunks, so a large file does not fill the memory. A missing file is an error, and the function returns no digest.

The hexadecimal form has two digits for each byte, so a byte below 0x10 has a leading zero. The solutions give lowercase digits.

Solutions

  • Python. hashlib.sha256(text.encode("utf-8")).hexdigest(). The hexdigest method gives the digest as hexadecimal digits. For a file, hashlib.file_digest(f, "sha256") reads the file. The documentation says that the file must be open for reading in binary mode, so the solution opens it with "rb".
  • JavaScript and TypeScript (Node.js). createHash("sha256").update(text, "utf8").digest("hex"). When the data is a string and no encoding is given, hash.update uses UTF-8. The solution gives "utf8" to make this visible. For a file, a for await loop reads the chunks of fs.createReadStream and gives each chunk to hash.update. The TypeScript file adds types only.
  • Java. MessageDigest.getInstance("SHA-256"). Every Java platform must support SHA-256, so the solution turns the checked NoSuchAlgorithmException into an AssertionError. digest(text.getBytes(UTF_8)) gives the bytes, and HexFormat.of().formatHex gives lowercase digits with no delimiter. For a file, a loop reads an InputStream into a buffer and calls update.
  • C#. SHA256.HashData(Encoding.UTF8.GetBytes(text)), then Convert.ToHexStringLower. Convert.ToHexString gives uppercase digits. For a file, SHA256.HashData(stream) with a stream from File.OpenRead.
  • Go. sha256.Sum256([]byte(text)) returns a [32]byte array, and hex.EncodeToString(sum[:]) gives lowercase digits. For a file, sha256.New() gives a hash.Hash, and io.Copy writes the file into it. The test checks the error of a missing file with errors.Is(err, fs.ErrNotExist).
  • Rust. The standard library has no SHA-256. The solution is a short implementation of FIPS 180-4: the 64 constants of section 4.2.2, the initial hash value of section 5.3.3, the padding of section 5.1.1, and the computation of section 6.2.2. A Sha256 value takes the message in parts with update, and finalize returns the 32 bytes. sha256_file returns io::Result<String>. A program with dependencies can use a crate for SHA-256 in place of this code.
  • C. The standard library has no SHA-256. The solution implements FIPS 180-4 as in Rust, with sha256_init, sha256_update and sha256_final. sha256_hex(data, len, out) writes 64 digits and a NUL into out. sha256_file reads the file with fread and returns -1 with errno set on an error.
  • C++. The standard library has no SHA-256. The solution is the same algorithm as a class Sha256 with update and finalize. sha256_file returns std::expected<std::string, HashError>, so the caller must check the result.
  • Bash. Bash has no SHA-256. The solution calls sha256sum from GNU coreutils. printf '%s' "$text" | sha256sum hashes the bytes of the text with no newline. With no file operand, sha256sum reads the standard input, so the solution gives the file with <"$path". The output starts with the digest, and ${out%% *} keeps the part before the first space.

Edge cases

The cases of sha256_text are in cases/basic.jsonl and cases/edge.jsonl. The expected digests of abc and of the 56-byte message abcdbcdecdef...nopq are the one-block and two-block samples of the NIST example values.

  • empty: the empty string has a digest too. It is e3b0c442...b855.
  • a-55, a-56, a-63 and a-64: the padding adds a 1 bit and a 64-bit length. A message of 55 bytes fills one block of 64 bytes with its padding. A message of 56 bytes needs a second block. These cases catch an error in the padding of the Rust, C and C++ solutions.
  • multi-block-112: a message of 112 bytes. With its padding, it is two blocks of 64 bytes.
  • non-ascii: characters of 2, 3 and 4 bytes in UTF-8.
  • nfc-cafe and nfd-cafe: the same visible word café in two forms. NFC has é as one code point. NFD has e and a combining accent. The bytes differ, so the digests differ.
  • trailing-newline: abc and abc\n have different digests.

The cases of sha256_file are in cases/files.jsonl, with the files in fixtures/: abc, abc\n, abc\r\n, an empty file, and three bytes 00 01 ff. The toolchain does not load this file, so each test file holds these cases by name. Each test file also hashes a file of one million a bytes, which is more than one chunk. The case missing-file in cases/errors.jsonl gives a path that does not exist. Each solution reports a "not found" error.

The Rust, C and C++ tests also check the ten SHA-256 messages of the NIST additional test data, and check that a message in parts of 1 to 130 bytes gives the same digest as the full message.

Pitfalls

  • echo adds a newline in Bash. The digest is of the text and the newline:

This code runs but gives a wrong answer on purpose.

echo abc | sha256sum
printf '%s' abc | sha256sum
Output
edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb  -
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad  -

Use printf '%s'. The same mistake happens when a program reads a line from a file and keeps the line terminator.

  • BigInteger.toString(16) drops the leading zeros in Java. The digest of id-45 starts with the digit 0:

This code runs but gives a wrong answer on purpose.

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;

public class Main {
    public static void main(String[] args) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] digest = md.digest("id-45".getBytes(StandardCharsets.UTF_8));
        String wrong = new BigInteger(1, digest).toString(16);
        String right = HexFormat.of().formatHex(digest);
        System.out.println(wrong.length() + " " + wrong);
        System.out.println(right.length() + " " + right);
    }
}
Output
63 f7f3525a5254a898edc33391b8a4ebd1a6afe61833e368469dd54f07fa40b7b
64 0f7f3525a5254a898edc33391b8a4ebd1a6afe61833e368469dd54f07fa40b7b

A compare with a stored digest of 64 digits fails. HexFormat gives two digits for each byte.

  • The bytes and the case of the digits must match in C#. Encoding.Unicode is UTF-16 in little-endian byte order, so it gives other bytes and another digest. Convert.ToHexString gives uppercase digits, so a compare with a lowercase digest is false:

This code runs but gives a wrong answer on purpose.

using System.Security.Cryptography;
using System.Text;

string want = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
byte[] utf16 = SHA256.HashData(Encoding.Unicode.GetBytes("abc"));
byte[] utf8 = SHA256.HashData(Encoding.UTF8.GetBytes("abc"));
Console.WriteLine(Convert.ToHexStringLower(utf16));
Console.WriteLine(Convert.ToHexString(utf8));
Console.WriteLine(Convert.ToHexString(utf8) == want);
Console.WriteLine(Convert.ToHexStringLower(utf8) == want);
Output
13e228567e8249fce53337f25d7970de3bd68ab2653424c7b8f9fd05e33caedf
BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD
False
True
  • Equal text can have different bytes. Two strings that look the same can have different code points. Python shows it with unicodedata.normalize:
import hashlib
import unicodedata

nfc = "caf\u00e9"
nfd = unicodedata.normalize("NFD", nfc)
print(nfc == nfd, len(nfc), len(nfd))
print(hashlib.sha256(nfc.encode("utf-8")).hexdigest())
print(hashlib.sha256(nfd.encode("utf-8")).hexdigest())
print(hashlib.sha256(unicodedata.normalize("NFC", nfd).encode("utf-8")).hexdigest())
Output
False 4 5
850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e
81ef060bcd98adc7824eb5c1ada83c32491b16018e11e79f00ab9d09e04b015a
850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e

If two systems must agree on the digest of text, they must agree on one normalization form before they hash. The solutions on this page do not normalize, because a file or a message must keep its bytes.

  • A Hash object in Node.js gives one digest only. After digest, the object cannot be used again, and a second call throws an error:
import { createHash } from "node:crypto";

const hash = createHash("sha256").update("abc");
console.log(hash.digest("hex"));
try {
  hash.digest("hex");
} catch (e) {
  console.log(e.code);
}
Output
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
ERR_CRYPTO_HASH_FINALIZED

Make a new Hash for each message.

  • A plain SHA-256 is not a password hash. The Python documentation says that naive algorithms such as sha1(password) are not resistant to brute-force attacks. Also, the same password always gives the same digest. So two users with the same password have the same stored value:

This code runs but gives a wrong answer on purpose.

import hashlib

for user in ["ana", "ben"]:
    print(user, hashlib.sha256(b"hunter2").hexdigest())
Output
ana f52fbd32b2b3b86ff88ef6c490628285f482af15ddcb29541f94bcf526a3f6c7
ben f52fbd32b2b3b86ff88ef6c490628285f482af15ddcb29541f94bcf526a3f6c7

NIST SP 800-63B-4 says that passwords shall be salted and hashed with a suitable password hashing scheme. The Python documentation says that a password hash must be tunable, slow, and include a salt. hashlib.pbkdf2_hmac and hashlib.scrypt are two such functions in the standard library. Store the salt with the hash. Compare with hmac.compare_digest, which the hmac documentation recommends in place of == to reduce the risk of a timing attack:

import hashlib
import hmac
import os


def hash_password(password: str, salt: bytes) -> bytes:
    return hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 600_000)


salt_ana, salt_ben = os.urandom(16), os.urandom(16)
stored_ana = hash_password("hunter2", salt_ana)
stored_ben = hash_password("hunter2", salt_ben)
print("same stored value:", stored_ana == stored_ben)
print("hunter2:", hmac.compare_digest(stored_ana, hash_password("hunter2", salt_ana)))
print("hunter3:", hmac.compare_digest(stored_ana, hash_password("hunter3", salt_ana)))
Output
same stored value: False
hunter2: True
hunter3: False

The iteration count sets the cost. SP 800-63B-4 says that the cost should be as high as practical.

Code

The build runs the native tests of each language in a pinned toolchain.

sha256_hash.pyI0tests passRawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

import hashlib
import os


def sha256_text(text: str) -> str:
    """Return the SHA-256 of the UTF-8 bytes of text, as lowercase hex."""
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def sha256_file(path: str | os.PathLike[str]) -> str:
    """Return the SHA-256 of the bytes of the file at path, as lowercase hex.

    The file is read in chunks, so a large file does not fill the memory.
    """
    # file_digest needs a file opened in binary mode.
    with open(path, "rb") as file:
        return hashlib.file_digest(file, "sha256").hexdigest()
test_sha256_hash.py 66 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

import pytest

from sha256_hash import sha256_file, sha256_text

# name: (text, the SHA-256 of its UTF-8 bytes)
TEXT_CASES = {
    "abc": ("abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"),
    "two-block-56": (
        "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
        "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
    ),
    "fox": (
        "The quick brown fox jumps over the lazy dog",
        "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592",
    ),
    "empty": ("", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"),
    "a-55": ("a" * 55, "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318"),
    "a-56": ("a" * 56, "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a"),
    "a-63": ("a" * 63, "7d3e74a05d7db15bce4ad9ec0658ea98e3f06eeecf16b4c6fff2da457ddc2f34"),
    "a-64": ("a" * 64, "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb"),
    "multi-block-112": (
        "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"
        "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
        "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1",
    ),
    "non-ascii": (
        "naïve café 日本語 🙂",
        "9c53e090acd67abd65c64ee431a36bdc36c3fd86341f5814a94d1b901ca9ed8d",
    ),
    "nfc-cafe": ("caf\u00e9", "850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e"),
    "nfd-cafe": ("cafe\u0301", "81ef060bcd98adc7824eb5c1ada83c32491b16018e11e79f00ab9d09e04b015a"),
    "trailing-newline": ("abc\n", "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"),
}

# name: (the bytes of the file, its SHA-256), from cases/files.jsonl
FILE_CASES = {
    "abc-file": (b"abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"),
    "abc-newline-file": (b"abc\n", "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"),
    "abc-crlf-file": (b"abc\r\n", "552bab6864c7a7b69a502ed1854b9245c0e1a30f008aaa0b281da62585fdb025"),
    "empty-file": (b"", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"),
    "binary-file": (b"\x00\x01\xff", "26a66b061e8f48f39927c312f25293959729eee95978e2892d49d3512a5cc092"),
    # One million repetitions of "a": more than one chunk.
    "million-a-file": (b"a" * 1_000_000, "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"),
}


@pytest.mark.parametrize("name", TEXT_CASES)
def test_text(name):
    text, want = TEXT_CASES[name]
    assert sha256_text(text) == want


@pytest.mark.parametrize("name", FILE_CASES)
def test_file(name, tmp_path):
    data, want = FILE_CASES[name]
    path = tmp_path / "in.bin"
    path.write_bytes(data)
    assert sha256_file(path) == want


def test_missing_file(tmp_path):
    with pytest.raises(FileNotFoundError):
        sha256_file(tmp_path / "missing.txt")
sha256_hash.cppI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

// SHA-256 as FIPS 180-4 defines it. The C++ standard library has no SHA-256.

#include "sha256_hash.hpp"

#include <algorithm>
#include <bit>
#include <fstream>

namespace {

// FIPS 180-4, 4.2.2: the first 32 bits of the fractional parts of the cube
// roots of the first 64 primes.
constexpr std::array<std::uint32_t, 64> K = {
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
};

// FIPS 180-4, 5.3.3: the initial hash value.
constexpr std::array<std::uint32_t, 8> H0 = {
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
};

// FIPS 180-4, 6.2.2: the hash computation for one 512-bit block.
void compress(std::array<std::uint32_t, 8>& state, const std::array<std::uint8_t, 64>& block) {
    using std::rotr;
    std::array<std::uint32_t, 64> w{};
    for (std::size_t t = 0; t < 16; ++t) {
        w[t] = std::uint32_t{block[4 * t]} << 24 | std::uint32_t{block[4 * t + 1]} << 16 |
               std::uint32_t{block[4 * t + 2]} << 8 | std::uint32_t{block[4 * t + 3]};
    }
    for (std::size_t t = 16; t < 64; ++t) {
        std::uint32_t s0 = rotr(w[t - 15], 7) ^ rotr(w[t - 15], 18) ^ (w[t - 15] >> 3);
        std::uint32_t s1 = rotr(w[t - 2], 17) ^ rotr(w[t - 2], 19) ^ (w[t - 2] >> 10);
        w[t] = s1 + w[t - 7] + s0 + w[t - 16];
    }
    auto [a, b, c, d, e, f, g, h] = state;
    for (std::size_t t = 0; t < 64; ++t) {
        std::uint32_t t1 = h + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[t] + w[t];
        std::uint32_t t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));
        h = g;
        g = f;
        f = e;
        e = d + t1;
        d = c;
        c = b;
        b = a;
        a = t1 + t2;
    }
    const std::array<std::uint32_t, 8> v = {a, b, c, d, e, f, g, h};
    for (std::size_t i = 0; i < 8; ++i) {
        state[i] += v[i];
    }
}

}  // namespace

Sha256::Sha256() : state_(H0) {}

void Sha256::update(std::span<const std::byte> data) {
    len_ += data.size();
    while (!data.empty()) {
        std::size_t n = std::min(64 - used_, data.size());
        for (std::size_t i = 0; i < n; ++i) {
            block_[used_ + i] = static_cast<std::uint8_t>(data[i]);
        }
        used_ += n;
        data = data.subspan(n);
        if (used_ == 64) {
            compress(state_, block_);
            used_ = 0;
        }
    }
}

Sha256::Digest Sha256::finalize() {
    // FIPS 180-4, 5.1.1: a 1 bit, then zero bits, then the length in bits as
    // a 64-bit big-endian number, to a multiple of 512 bits.
    const std::uint64_t bits = len_ * 8;
    block_[used_++] = 0x80;
    if (used_ > 56) {
        // No room for the length: it goes in one more block.
        std::fill(block_.begin() + used_, block_.end(), 0);
        compress(state_, block_);
        used_ = 0;
    }
    std::fill(block_.begin() + used_, block_.begin() + 56, 0);
    for (std::size_t i = 0; i < 8; ++i) {
        block_[56 + i] = static_cast<std::uint8_t>(bits >> (56 - 8 * i));
    }
    compress(state_, block_);
    Digest out{};
    for (std::size_t i = 0; i < 8; ++i) {
        out[4 * i] = static_cast<std::uint8_t>(state_[i] >> 24);
        out[4 * i + 1] = static_cast<std::uint8_t>(state_[i] >> 16);
        out[4 * i + 2] = static_cast<std::uint8_t>(state_[i] >> 8);
        out[4 * i + 3] = static_cast<std::uint8_t>(state_[i]);
    }
    return out;
}

std::string to_hex(const Sha256::Digest& digest) {
    constexpr std::string_view digits = "0123456789abcdef";
    std::string out;
    out.reserve(64);
    for (std::uint8_t b : digest) {
        out += digits[b >> 4];
        out += digits[b & 0x0f];
    }
    return out;
}

std::string sha256_text(std::string_view text) {
    Sha256 h;
    h.update(text);
    return to_hex(h.finalize());
}

std::expected<std::string, HashError> sha256_file(const std::filesystem::path& path) {
    std::ifstream in(path, std::ios::binary);
    if (!in) {
        return std::unexpected(HashError::cannot_open);
    }
    Sha256 h;
    std::array<char, 8192> buf;
    // The file is read in chunks, so a large file does not fill the memory.
    while (in.read(buf.data(), buf.size()) || in.gcount() > 0) {
        h.update(std::string_view(buf.data(), static_cast<std::size_t>(in.gcount())));
    }
    if (in.bad()) {
        return std::unexpected(HashError::read_failed);
    }
    return to_hex(h.finalize());
}
sha256_hash.hpp 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.
// since: C++23 (std::expected)

#pragma once

#include <array>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <span>
#include <string>
#include <string_view>

// A SHA-256 computation that takes the message in parts (FIPS 180-4).
class Sha256 {
public:
    using Digest = std::array<std::uint8_t, 32>;

    Sha256();
    // Adds the bytes of data to the message.
    void update(std::span<const std::byte> data);
    void update(std::string_view data) { update(std::as_bytes(std::span(data))); }
    // Pads the message and returns the digest. Call it once.
    Digest finalize();

private:
    std::array<std::uint32_t, 8> state_;
    std::array<std::uint8_t, 64> block_{};
    std::size_t used_ = 0;
    std::uint64_t len_ = 0;  // the length of the message in bytes
};

// Returns the digest as 64 lowercase hexadecimal digits.
std::string to_hex(const Sha256::Digest& digest);

// Returns the SHA-256 of the bytes of text, as lowercase hex. For text, pass
// its UTF-8 bytes.
std::string sha256_text(std::string_view text);

enum class HashError { cannot_open, read_failed };

// Returns the SHA-256 of the bytes of the file at path, as lowercase hex.
std::expected<std::string, HashError> sha256_file(const std::filesystem::path& path);
test_sha256_hash.cpp 124 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <string>
#include <string_view>
#include <vector>

#include "sha256_hash.hpp"

namespace {

int failures = 0;

void check(std::string_view name, const std::string& got, std::string_view want) {
    if (got != want) {
        std::fprintf(stderr, "case %.*s failed: got %s\n", static_cast<int>(name.size()), name.data(),
                     got.c_str());
        ++failures;
    }
}

struct Case {
    std::string name, data, want;
};

}  // namespace

int main() {
    using namespace std::string_literals;
    const std::vector<Case> text_cases = {
        {"abc", "abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"},
        {"two-block-56", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
         "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"},
        {"fox", "The quick brown fox jumps over the lazy dog",
         "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"},
        {"empty", "", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"},
        {"a-55", std::string(55, 'a'), "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318"},
        {"a-56", std::string(56, 'a'), "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a"},
        {"a-63", std::string(63, 'a'), "7d3e74a05d7db15bce4ad9ec0658ea98e3f06eeecf16b4c6fff2da457ddc2f34"},
        {"a-64", std::string(64, 'a'), "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb"},
        {"multi-block-112",
         "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"
         "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
         "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1"},
        {"non-ascii", "na\xc3\xafve caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e \xf0\x9f\x99\x82",
         "9c53e090acd67abd65c64ee431a36bdc36c3fd86341f5814a94d1b901ca9ed8d"},
        {"nfc-cafe", "caf\xc3\xa9", "850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e"},
        {"nfd-cafe", "cafe\xcc\x81", "81ef060bcd98adc7824eb5c1ada83c32491b16018e11e79f00ab9d09e04b015a"},
        {"trailing-newline", "abc\n", "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"},
    };
    for (const auto& c : text_cases) {
        check(c.name, sha256_text(c.data), c.want);
    }

    // The SHA-256 Test Data of the NIST example values, SHA2_Additional.pdf.
    const std::vector<Case> nist_cases = {
        {"nist-1", "\xbd", "68325720aabd7c82f30f554b313d0570c95accbb7dc4b5aae11204c08ffe732b"},
        {"nist-2", "\xc9\x8c\x8e\x55", "7abc22c0ae5af26ce93dbb94433a0e0b2e119d014f8e7f65bd56c61ccccd9504"},
        {"nist-3", std::string(55, '\0'), "02779466cdec163811d078815c633f21901413081449002f24aa3e80f0b88ef7"},
        {"nist-4", std::string(56, '\0'), "d4817aa5497628e7c77e6b606107042bbba3130888c5f47a375e6179be789fbb"},
        {"nist-5", std::string(57, '\0'), "65a16cb7861335d5ace3c60718b5052e44660726da4cd13bb745381b235a1785"},
        {"nist-6", std::string(64, '\0'), "f5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b"},
        {"nist-7", std::string(1000, '\0'), "541b3e9daa09b20bf85fa273e5cbd3e80185aa4ec298e765db87742b70138a53"},
        {"nist-8", std::string(1000, 'A'), "c2e686823489ced2017f6059b8b239318b6364f6dcd835d0a519105a1eadd6e4"},
        {"nist-9", std::string(1005, 'U'), "f4d62ddec0f3dd90ea1380fa16a5ff8dc4c54b21740650f24afc4120903552b0"},
        {"nist-10", std::string(1000000, '\0'), "d29751f2649b32ff572b5e0a9f541ea660a50f94ff0beedfb0b692b924cc8025"},
    };
    for (const auto& c : nist_cases) {
        check(c.name, sha256_text(c.data), c.want);
    }

    // From cases/files.jsonl.
    const std::vector<Case> file_cases = {
        {"abc-file", "abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"},
        {"abc-newline-file", "abc\n", "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"},
        {"abc-crlf-file", "abc\r\n", "552bab6864c7a7b69a502ed1854b9245c0e1a30f008aaa0b281da62585fdb025"},
        {"empty-file", "", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"},
        {"binary-file", "\x00\x01\xff"s, "26a66b061e8f48f39927c312f25293959729eee95978e2892d49d3512a5cc092"},
        // One million repetitions of "a": more than one chunk.
        {"million-a-file", std::string(1000000, 'a'),
         "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"},
    };
    const std::filesystem::path input = "sha256_hash_input.bin";
    for (const auto& c : file_cases) {
        {
            std::ofstream out(input, std::ios::binary);
            out << c.data;
        }
        auto got = sha256_file(input);
        check(c.name, got.value_or("error"), c.want);
    }
    std::filesystem::remove(input);

    auto missing = sha256_file("sha256_hash_missing.txt");
    if (missing.has_value() || missing.error() != HashError::cannot_open) {
        std::fprintf(stderr, "case missing-file failed\n");
        ++failures;
    }

    // The message in parts of 1, 2, ..., 130 bytes gives the same digest as in one part.
    std::string data(1000, '\0');
    for (std::size_t i = 0; i < data.size(); ++i) {
        data[i] = static_cast<char>(i % 251);
    }
    const std::string want = sha256_text(data);
    for (std::size_t size = 1; size <= 130; ++size) {
        Sha256 h;
        for (std::size_t i = 0; i < data.size(); i += size) {
            h.update(std::string_view(data).substr(i, size));
        }
        check("parts of " + std::to_string(size), to_hex(h.finalize()), want);
    }

    if (failures > 0) {
        std::fprintf(stderr, "%d failures\n", failures);
        return EXIT_FAILURE;
    }
    std::puts("ok");
    return EXIT_SUCCESS;
}
Sha256Hash.javaI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;

public final class Sha256Hash {
  private Sha256Hash() {}

  // Every Java platform must support SHA-256, so this cannot fail.
  private static MessageDigest sha256() {
    try {
      return MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
      throw new AssertionError(e);
    }
  }

  /** Returns the SHA-256 of the UTF-8 bytes of text, as lowercase hex. */
  public static String sha256Text(String text) {
    byte[] digest = sha256().digest(text.getBytes(StandardCharsets.UTF_8));
    // HexFormat keeps the leading zeros: always two digits per byte.
    return HexFormat.of().formatHex(digest);
  }

  /**
   * Returns the SHA-256 of the bytes of the file at path, as lowercase hex. The file is read in
   * chunks, so a large file does not fill the memory.
   */
  public static String sha256File(Path path) throws IOException {
    MessageDigest md = sha256();
    byte[] buffer = new byte[8192];
    try (InputStream in = Files.newInputStream(path)) {
      int n;
      while ((n = in.read(buffer)) != -1) {
        md.update(buffer, 0, n);
      }
    }
    return HexFormat.of().formatHex(md.digest());
  }
}
Sha256HashTest.java 125 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class Sha256HashTest {
  @TempDir Path dir;

  static Stream<Arguments> textCases() {
    return Stream.of(
        Arguments.of(
            "abc", "abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"),
        Arguments.of(
            "two-block-56",
            "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
            "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"),
        Arguments.of(
            "fox",
            "The quick brown fox jumps over the lazy dog",
            "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"),
        Arguments.of(
            "empty", "", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"),
        Arguments.of(
            "a-55",
            "a".repeat(55),
            "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318"),
        Arguments.of(
            "a-56",
            "a".repeat(56),
            "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a"),
        Arguments.of(
            "a-63",
            "a".repeat(63),
            "7d3e74a05d7db15bce4ad9ec0658ea98e3f06eeecf16b4c6fff2da457ddc2f34"),
        Arguments.of(
            "a-64",
            "a".repeat(64),
            "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb"),
        Arguments.of(
            "multi-block-112",
            "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"
                + "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
            "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1"),
        Arguments.of(
            "non-ascii",
            "naïve café 日本語 🙂",
            "9c53e090acd67abd65c64ee431a36bdc36c3fd86341f5814a94d1b901ca9ed8d"),
        Arguments.of(
            "nfc-cafe",
            "caf\u00e9",
            "850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e"),
        Arguments.of(
            "nfd-cafe",
            "cafe\u0301",
            "81ef060bcd98adc7824eb5c1ada83c32491b16018e11e79f00ab9d09e04b015a"),
        Arguments.of(
            "trailing-newline",
            "abc\n",
            "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"));
  }

  static Stream<Arguments> fileCases() {
    byte[] millionA = new byte[1_000_000];
    Arrays.fill(millionA, (byte) 'a');
    return Stream.of(
        Arguments.of(
            "abc-file",
            "abc".getBytes(StandardCharsets.US_ASCII),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"),
        Arguments.of(
            "abc-newline-file",
            "abc\n".getBytes(StandardCharsets.US_ASCII),
            "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"),
        Arguments.of(
            "abc-crlf-file",
            "abc\r\n".getBytes(StandardCharsets.US_ASCII),
            "552bab6864c7a7b69a502ed1854b9245c0e1a30f008aaa0b281da62585fdb025"),
        Arguments.of(
            "empty-file",
            new byte[0],
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"),
        Arguments.of(
            "binary-file",
            new byte[] {0x00, 0x01, (byte) 0xff},
            "26a66b061e8f48f39927c312f25293959729eee95978e2892d49d3512a5cc092"),
        // One million repetitions of "a": more than one chunk.
        Arguments.of(
            "million-a-file",
            millionA,
            "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("textCases")
  void hashesText(String name, String text, String want) {
    assertEquals(want, Sha256Hash.sha256Text(text), name);
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("fileCases")
  void hashesFile(String name, byte[] data, String want) throws IOException {
    Path path = dir.resolve("in.bin");
    Files.write(path, data);
    assertEquals(want, Sha256Hash.sha256File(path), name);
  }

  @Test
  void missingFile() {
    assertThrows(NoSuchFileException.class, () -> Sha256Hash.sha256File(dir.resolve("missing.txt")));
  }
}
sha256_hash.cI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

// SHA-256 as FIPS 180-4 defines it. The C standard library has no SHA-256.

#include "sha256_hash.h"

#include <errno.h>
#include <stdio.h>
#include <string.h>

// FIPS 180-4, 4.2.2: the first 32 bits of the fractional parts of the cube
// roots of the first 64 primes.
static const uint32_t K[64] = {
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
};

// FIPS 180-4, 5.3.3: the initial hash value.
static const uint32_t H0[8] = {
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
};

static uint32_t rotr(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); }

// FIPS 180-4, 6.2.2: the hash computation for one 512-bit block.
static void compress(uint32_t state[8], const unsigned char block[64]) {
    uint32_t w[64];
    for (int t = 0; t < 16; t++) {
        const unsigned char *p = block + 4 * t;
        w[t] = (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3];
    }
    for (int t = 16; t < 64; t++) {
        uint32_t s0 = rotr(w[t - 15], 7) ^ rotr(w[t - 15], 18) ^ (w[t - 15] >> 3);
        uint32_t s1 = rotr(w[t - 2], 17) ^ rotr(w[t - 2], 19) ^ (w[t - 2] >> 10);
        w[t] = s1 + w[t - 7] + s0 + w[t - 16];
    }
    uint32_t a = state[0], b = state[1], c = state[2], d = state[3];
    uint32_t e = state[4], f = state[5], g = state[6], h = state[7];
    for (int t = 0; t < 64; t++) {
        uint32_t t1 = h + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[t] + w[t];
        uint32_t t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));
        h = g;
        g = f;
        f = e;
        e = d + t1;
        d = c;
        c = b;
        b = a;
        a = t1 + t2;
    }
    state[0] += a;
    state[1] += b;
    state[2] += c;
    state[3] += d;
    state[4] += e;
    state[5] += f;
    state[6] += g;
    state[7] += h;
}

void sha256_init(struct sha256 *h) {
    memcpy(h->state, H0, sizeof H0);
    h->used = 0;
    h->len = 0;
}

void sha256_update(struct sha256 *h, const void *data, size_t len) {
    const unsigned char *p = data;
    h->len += len;
    while (len > 0) {
        size_t n = 64 - h->used;
        if (n > len) {
            n = len;
        }
        memcpy(h->block + h->used, p, n);
        h->used += n;
        p += n;
        len -= n;
        if (h->used == 64) {
            compress(h->state, h->block);
            h->used = 0;
        }
    }
}

void sha256_final(struct sha256 *h, unsigned char digest[32]) {
    // FIPS 180-4, 5.1.1: a 1 bit, then zero bits, then the length in bits as
    // a 64-bit big-endian number, to a multiple of 512 bits.
    uint64_t bits = h->len * 8;
    h->block[h->used++] = 0x80;
    if (h->used > 56) {
        // No room for the length: it goes in one more block.
        memset(h->block + h->used, 0, 64 - h->used);
        compress(h->state, h->block);
        h->used = 0;
    }
    memset(h->block + h->used, 0, 56 - h->used);
    for (int i = 0; i < 8; i++) {
        h->block[56 + i] = (unsigned char)(bits >> (56 - 8 * i));
    }
    compress(h->state, h->block);
    for (int i = 0; i < 8; i++) {
        digest[4 * i] = (unsigned char)(h->state[i] >> 24);
        digest[4 * i + 1] = (unsigned char)(h->state[i] >> 16);
        digest[4 * i + 2] = (unsigned char)(h->state[i] >> 8);
        digest[4 * i + 3] = (unsigned char)h->state[i];
    }
}

static void to_hex(const unsigned char digest[32], char out[65]) {
    static const char digits[] = "0123456789abcdef";
    for (int i = 0; i < 32; i++) {
        out[2 * i] = digits[digest[i] >> 4];
        out[2 * i + 1] = digits[digest[i] & 0x0f];
    }
    out[64] = '\0';
}

void sha256_hex(const void *data, size_t len, char out[65]) {
    struct sha256 h;
    unsigned char digest[32];
    sha256_init(&h);
    sha256_update(&h, data, len);
    sha256_final(&h, digest);
    to_hex(digest, out);
}

int sha256_file(const char *path, char out[65]) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return -1;
    }
    struct sha256 h;
    unsigned char buf[8192];
    size_t n;
    sha256_init(&h);
    // The file is read in chunks, so a large file does not fill the memory.
    while ((n = fread(buf, 1, sizeof buf, f)) > 0) {
        sha256_update(&h, buf, n);
    }
    if (ferror(f)) {
        int err = errno;
        fclose(f);
        errno = err;
        return -1;
    }
    fclose(f);
    unsigned char digest[32];
    sha256_final(&h, digest);
    to_hex(digest, out);
    return 0;
}
sha256_hash.h 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

#ifndef SHA256_HASH_H
#define SHA256_HASH_H

#include <stddef.h>
#include <stdint.h>

// A SHA-256 computation that takes the message in parts (FIPS 180-4).
struct sha256 {
    uint32_t state[8];
    unsigned char block[64];
    size_t used;
    uint64_t len; // the length of the message in bytes
};

void sha256_init(struct sha256 *h);
void sha256_update(struct sha256 *h, const void *data, size_t len);
void sha256_final(struct sha256 *h, unsigned char digest[32]);

// Writes the SHA-256 of the len bytes at data to out, as 64 lowercase hex
// digits and a NUL. For text, pass its UTF-8 bytes.
void sha256_hex(const void *data, size_t len, char out[65]);

// Writes the SHA-256 of the bytes of the file at path to out, as in
// sha256_hex. It returns 0, or -1 with errno set.
int sha256_file(const char *path, char out[65]);

#endif
test_sha256_hash.c 180 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

#define _POSIX_C_SOURCE 200809L

#include "sha256_hash.h"

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

// A message is the bytes of a literal, or len copies of the byte fill.
#define S(s) s, sizeof(s) - 1, 0
#define REP(fill, n) NULL, n, fill

struct test_case {
    const char *name;
    const char *data; // NULL: len copies of fill
    size_t len;
    char fill;
    const char *want;
};

static const struct test_case text_cases[] = {
    {"abc", S("abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"},
    {"two-block-56", S("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
     "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"},
    {"fox", S("The quick brown fox jumps over the lazy dog"),
     "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"},
    {"empty", S(""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"},
    {"a-55", REP('a', 55), "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318"},
    {"a-56", REP('a', 56), "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a"},
    {"a-63", REP('a', 63), "7d3e74a05d7db15bce4ad9ec0658ea98e3f06eeecf16b4c6fff2da457ddc2f34"},
    {"a-64", REP('a', 64), "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb"},
    {"multi-block-112",
     S("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"
       "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"),
     "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1"},
    {"non-ascii", S("na\xc3\xafve caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e \xf0\x9f\x99\x82"),
     "9c53e090acd67abd65c64ee431a36bdc36c3fd86341f5814a94d1b901ca9ed8d"},
    {"nfc-cafe", S("caf\xc3\xa9"), "850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e"},
    {"nfd-cafe", S("cafe\xcc\x81"), "81ef060bcd98adc7824eb5c1ada83c32491b16018e11e79f00ab9d09e04b015a"},
    {"trailing-newline", S("abc\n"), "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"},
};

// From cases/files.jsonl.
static const struct test_case file_cases[] = {
    {"abc-file", S("abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"},
    {"abc-newline-file", S("abc\n"), "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"},
    {"abc-crlf-file", S("abc\r\n"), "552bab6864c7a7b69a502ed1854b9245c0e1a30f008aaa0b281da62585fdb025"},
    {"empty-file", S(""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"},
    {"binary-file", S("\x00\x01\xff"), "26a66b061e8f48f39927c312f25293959729eee95978e2892d49d3512a5cc092"},
    // One million repetitions of "a": more than one chunk.
    {"million-a-file", REP('a', 1000000), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"},
};

// The SHA-256 Test Data of the NIST example values, SHA2_Additional.pdf.
static const struct test_case nist_cases[] = {
    {"nist-1", S("\xbd"), "68325720aabd7c82f30f554b313d0570c95accbb7dc4b5aae11204c08ffe732b"},
    {"nist-2", S("\xc9\x8c\x8e\x55"), "7abc22c0ae5af26ce93dbb94433a0e0b2e119d014f8e7f65bd56c61ccccd9504"},
    {"nist-3", REP(0, 55), "02779466cdec163811d078815c633f21901413081449002f24aa3e80f0b88ef7"},
    {"nist-4", REP(0, 56), "d4817aa5497628e7c77e6b606107042bbba3130888c5f47a375e6179be789fbb"},
    {"nist-5", REP(0, 57), "65a16cb7861335d5ace3c60718b5052e44660726da4cd13bb745381b235a1785"},
    {"nist-6", REP(0, 64), "f5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b"},
    {"nist-7", REP(0, 1000), "541b3e9daa09b20bf85fa273e5cbd3e80185aa4ec298e765db87742b70138a53"},
    {"nist-8", REP('A', 1000), "c2e686823489ced2017f6059b8b239318b6364f6dcd835d0a519105a1eadd6e4"},
    {"nist-9", REP('U', 1005), "f4d62ddec0f3dd90ea1380fa16a5ff8dc4c54b21740650f24afc4120903552b0"},
    {"nist-10", REP(0, 1000000), "d29751f2649b32ff572b5e0a9f541ea660a50f94ff0beedfb0b692b924cc8025"},
};

#define COUNT(a) (sizeof(a) / sizeof((a)[0]))

// Returns the bytes of the message of c in a new buffer.
static char *message(const struct test_case *c) {
    char *buf = malloc(c->len + 1);
    if (buf == NULL) {
        perror("malloc");
        exit(1);
    }
    if (c->data != NULL) {
        memcpy(buf, c->data, c->len);
    } else {
        memset(buf, c->fill, c->len);
    }
    return buf;
}

static int check(const char *name, const char *got, const char *want) {
    if (strcmp(got, want) != 0) {
        printf("FAIL %s: got %s, want %s\n", name, got, want);
        return 1;
    }
    return 0;
}

int main(void) {
    int failures = 0;
    char out[65];

    for (size_t i = 0; i < COUNT(text_cases); i++) {
        char *msg = message(&text_cases[i]);
        sha256_hex(msg, text_cases[i].len, out);
        failures += check(text_cases[i].name, out, text_cases[i].want);
        free(msg);
    }
    for (size_t i = 0; i < COUNT(nist_cases); i++) {
        char *msg = message(&nist_cases[i]);
        sha256_hex(msg, nist_cases[i].len, out);
        failures += check(nist_cases[i].name, out, nist_cases[i].want);
        free(msg);
    }

    char dir[64];
    snprintf(dir, sizeof dir, "/tmp/sha256-%ld", (long)getpid());
    if (mkdir(dir, 0700) != 0) {
        perror(dir);
        return 1;
    }
    char path[128];
    snprintf(path, sizeof path, "%s/in.bin", dir);
    for (size_t i = 0; i < COUNT(file_cases); i++) {
        const struct test_case *c = &file_cases[i];
        char *msg = message(c);
        FILE *f = fopen(path, "wb");
        if (f == NULL || fwrite(msg, 1, c->len, f) != c->len || fclose(f) != 0) {
            perror(path);
            return 1;
        }
        free(msg);
        if (sha256_file(path, out) != 0) {
            printf("FAIL %s: %s\n", c->name, strerror(errno));
            failures++;
        } else {
            failures += check(c->name, out, c->want);
        }
    }
    remove(path);

    snprintf(path, sizeof path, "%s/missing.txt", dir);
    errno = 0;
    if (sha256_file(path, out) != -1 || errno != ENOENT) {
        printf("FAIL missing-file: no ENOENT\n");
        failures++;
    }
    rmdir(dir);

    // The message in parts of 1, 2, ..., 130 bytes gives the same digest as in one part.
    unsigned char data[1000];
    for (size_t i = 0; i < sizeof data; i++) {
        data[i] = (unsigned char)(i % 251);
    }
    char want[65];
    sha256_hex(data, sizeof data, want);
    for (size_t size = 1; size <= 130; size++) {
        struct sha256 h;
        unsigned char digest[32];
        sha256_init(&h);
        for (size_t i = 0; i < sizeof data; i += size) {
            sha256_update(&h, data + i, sizeof data - i < size ? sizeof data - i : size);
        }
        sha256_final(&h, digest);
        for (int i = 0; i < 32; i++) {
            snprintf(out + 2 * i, 3, "%02x", digest[i]);
        }
        if (strcmp(out, want) != 0) {
            printf("FAIL parts of %zu\n", size);
            failures++;
        }
    }

    if (failures > 0) {
        printf("%d failures\n", failures);
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Sha256Hash.csI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

using System.Security.Cryptography;
using System.Text;

public static class Sha256Hash
{
    // Returns the SHA-256 of the UTF-8 bytes of text, as lowercase hex.
    public static string Sha256Text(string text)
    {
        byte[] digest = SHA256.HashData(Encoding.UTF8.GetBytes(text));
        // Convert.ToHexString gives uppercase digits.
        return Convert.ToHexStringLower(digest);
    }

    // Returns the SHA-256 of the bytes of the file at path, as lowercase hex.
    // HashData reads the stream in chunks, so a large file does not fill the memory.
    public static string Sha256File(string path)
    {
        using FileStream stream = File.OpenRead(path);
        return Convert.ToHexStringLower(SHA256.HashData(stream));
    }
}
Sha256HashTests.cs 62 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

using Xunit;

public sealed class Sha256HashTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("sha256-").FullName;

    public void Dispose() => Directory.Delete(dir, recursive: true);

    public static TheoryData<string, string, string> TextCases => new()
    {
        { "abc", "abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" },
        { "two-block-56", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" },
        { "fox", "The quick brown fox jumps over the lazy dog", "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592" },
        { "empty", "", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" },
        { "a-55", new string('a', 55), "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318" },
        { "a-56", new string('a', 56), "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a" },
        { "a-63", new string('a', 63), "7d3e74a05d7db15bce4ad9ec0658ea98e3f06eeecf16b4c6fff2da457ddc2f34" },
        { "a-64", new string('a', 64), "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb" },
        { "multi-block-112", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1" },
        { "non-ascii", "naïve café 日本語 \U0001F642", "9c53e090acd67abd65c64ee431a36bdc36c3fd86341f5814a94d1b901ca9ed8d" },
        { "nfc-cafe", "caf\u00e9", "850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e" },
        { "nfd-cafe", "cafe\u0301", "81ef060bcd98adc7824eb5c1ada83c32491b16018e11e79f00ab9d09e04b015a" },
        { "trailing-newline", "abc\n", "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb" },
    };

    // From cases/files.jsonl.
    public static TheoryData<string, byte[], string> FileCases => new()
    {
        { "abc-file", "abc"u8.ToArray(), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" },
        { "abc-newline-file", "abc\n"u8.ToArray(), "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb" },
        { "abc-crlf-file", "abc\r\n"u8.ToArray(), "552bab6864c7a7b69a502ed1854b9245c0e1a30f008aaa0b281da62585fdb025" },
        { "empty-file", [], "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" },
        { "binary-file", [0x00, 0x01, 0xff], "26a66b061e8f48f39927c312f25293959729eee95978e2892d49d3512a5cc092" },
        // One million repetitions of "a": more than one chunk.
        { "million-a-file", Enumerable.Repeat((byte)'a', 1_000_000).ToArray(), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0" },
    };

    [Theory]
    [MemberData(nameof(TextCases))]
    public void HashesText(string name, string text, string want)
    {
        Assert.True(want == Sha256Hash.Sha256Text(text), name);
    }

    [Theory]
    [MemberData(nameof(FileCases))]
    public void HashesFile(string name, byte[] data, string want)
    {
        string path = Path.Combine(dir, "in.bin");
        File.WriteAllBytes(path, data);
        Assert.True(want == Sha256Hash.Sha256File(path), name);
    }

    [Fact]
    public void MissingFile()
    {
        Assert.Throws<FileNotFoundException>(() => Sha256Hash.Sha256File(Path.Combine(dir, "missing.txt")));
    }
}
sha256Hash.jsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";

/**
 * Returns the SHA-256 of the UTF-8 bytes of text, as lowercase hex.
 * @param {string} text
 * @returns {string}
 */
export function sha256Text(text) {
  return createHash("sha256").update(text, "utf8").digest("hex");
}

/**
 * Returns the SHA-256 of the bytes of the file at path, as lowercase hex.
 * The file is read in chunks, so a large file does not fill the memory.
 * @param {string} path
 * @returns {Promise<string>}
 */
export async function sha256File(path) {
  const hash = createHash("sha256");
  // With no encoding, each chunk is a Buffer of the raw bytes.
  for await (const chunk of createReadStream(path)) {
    hash.update(chunk);
  }
  return hash.digest("hex");
}
sha256Hash.test.js 83 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";

import { sha256File, sha256Text } from "./sha256Hash.js";

// [case, text, the SHA-256 of its UTF-8 bytes]
const textCases = [
  ["abc", "abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"],
  [
    "two-block-56",
    "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
    "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
  ],
  [
    "fox",
    "The quick brown fox jumps over the lazy dog",
    "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592",
  ],
  ["empty", "", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"],
  ["a-55", "a".repeat(55), "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318"],
  ["a-56", "a".repeat(56), "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a"],
  ["a-63", "a".repeat(63), "7d3e74a05d7db15bce4ad9ec0658ea98e3f06eeecf16b4c6fff2da457ddc2f34"],
  ["a-64", "a".repeat(64), "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb"],
  [
    "multi-block-112",
    "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" +
      "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
    "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1",
  ],
  [
    "non-ascii",
    "naïve café 日本語 \u{1f642}",
    "9c53e090acd67abd65c64ee431a36bdc36c3fd86341f5814a94d1b901ca9ed8d",
  ],
  ["nfc-cafe", "caf\u00e9", "850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e"],
  ["nfd-cafe", "cafe\u0301", "81ef060bcd98adc7824eb5c1ada83c32491b16018e11e79f00ab9d09e04b015a"],
  ["trailing-newline", "abc\n", "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"],
];

// [case, the bytes of the file, its SHA-256], from cases/files.jsonl
const fileCases = [
  ["abc-file", Buffer.from("abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"],
  ["abc-newline-file", Buffer.from("abc\n"), "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"],
  ["abc-crlf-file", Buffer.from("abc\r\n"), "552bab6864c7a7b69a502ed1854b9245c0e1a30f008aaa0b281da62585fdb025"],
  ["empty-file", Buffer.alloc(0), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"],
  ["binary-file", Buffer.from([0x00, 0x01, 0xff]), "26a66b061e8f48f39927c312f25293959729eee95978e2892d49d3512a5cc092"],
  // One million repetitions of "a": more than one chunk.
  ["million-a-file", Buffer.alloc(1_000_000, "a"), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"],
];

for (const [name, text, want] of textCases) {
  test(name, () => {
    assert.equal(sha256Text(text), want);
  });
}

for (const [name, data, want] of fileCases) {
  test(name, async () => {
    const dir = await mkdtemp(join(tmpdir(), "sha256-"));
    try {
      const path = join(dir, "in.bin");
      await writeFile(path, data);
      assert.equal(await sha256File(path), want);
    } finally {
      await rm(dir, { recursive: true });
    }
  });
}

test("missing-file", async () => {
  const dir = await mkdtemp(join(tmpdir(), "sha256-"));
  try {
    await assert.rejects(sha256File(join(dir, "missing.txt")), { code: "ENOENT" });
  } finally {
    await rm(dir, { recursive: true });
  }
});
sha256Hash.tsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";

// Returns the SHA-256 of the UTF-8 bytes of text, as lowercase hex.
export function sha256Text(text: string): string {
  return createHash("sha256").update(text, "utf8").digest("hex");
}

// Returns the SHA-256 of the bytes of the file at path, as lowercase hex.
// The file is read in chunks, so a large file does not fill the memory.
export async function sha256File(path: string): Promise<string> {
  const hash = createHash("sha256");
  // With no encoding, each chunk is a Buffer of the raw bytes.
  for await (const chunk of createReadStream(path)) {
    hash.update(chunk as Buffer);
  }
  return hash.digest("hex");
}
sha256Hash.test.ts 83 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";

import { sha256File, sha256Text } from "./sha256Hash.ts";

// [case, text, the SHA-256 of its UTF-8 bytes]
const textCases: [string, string, string][] = [
  ["abc", "abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"],
  [
    "two-block-56",
    "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
    "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
  ],
  [
    "fox",
    "The quick brown fox jumps over the lazy dog",
    "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592",
  ],
  ["empty", "", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"],
  ["a-55", "a".repeat(55), "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318"],
  ["a-56", "a".repeat(56), "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a"],
  ["a-63", "a".repeat(63), "7d3e74a05d7db15bce4ad9ec0658ea98e3f06eeecf16b4c6fff2da457ddc2f34"],
  ["a-64", "a".repeat(64), "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb"],
  [
    "multi-block-112",
    "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" +
      "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
    "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1",
  ],
  [
    "non-ascii",
    "naïve café 日本語 \u{1f642}",
    "9c53e090acd67abd65c64ee431a36bdc36c3fd86341f5814a94d1b901ca9ed8d",
  ],
  ["nfc-cafe", "caf\u00e9", "850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e"],
  ["nfd-cafe", "cafe\u0301", "81ef060bcd98adc7824eb5c1ada83c32491b16018e11e79f00ab9d09e04b015a"],
  ["trailing-newline", "abc\n", "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"],
];

// [case, the bytes of the file, its SHA-256], from cases/files.jsonl
const fileCases: [string, Buffer, string][] = [
  ["abc-file", Buffer.from("abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"],
  ["abc-newline-file", Buffer.from("abc\n"), "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"],
  ["abc-crlf-file", Buffer.from("abc\r\n"), "552bab6864c7a7b69a502ed1854b9245c0e1a30f008aaa0b281da62585fdb025"],
  ["empty-file", Buffer.alloc(0), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"],
  ["binary-file", Buffer.from([0x00, 0x01, 0xff]), "26a66b061e8f48f39927c312f25293959729eee95978e2892d49d3512a5cc092"],
  // One million repetitions of "a": more than one chunk.
  ["million-a-file", Buffer.alloc(1_000_000, "a"), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"],
];

for (const [name, text, want] of textCases) {
  test(name, () => {
    assert.equal(sha256Text(text), want);
  });
}

for (const [name, data, want] of fileCases) {
  test(name, async () => {
    const dir = await mkdtemp(join(tmpdir(), "sha256-"));
    try {
      const path = join(dir, "in.bin");
      await writeFile(path, data);
      assert.equal(await sha256File(path), want);
    } finally {
      await rm(dir, { recursive: true });
    }
  });
}

test("missing-file", async () => {
  const dir = await mkdtemp(join(tmpdir(), "sha256-"));
  try {
    await assert.rejects(sha256File(join(dir, "missing.txt")), { code: "ENOENT" });
  } finally {
    await rm(dir, { recursive: true });
  }
});
sha256_hash.goI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

// Package sha256hash computes the SHA-256 of a string or of a file.
package sha256hash

import (
	"crypto/sha256"
	"encoding/hex"
	"io"
	"os"
)

// Sha256Text returns the SHA-256 of the UTF-8 bytes of text, as lowercase hex.
// A Go string holds bytes, so []byte(text) is the UTF-8 encoding of valid text.
func Sha256Text(text string) string {
	sum := sha256.Sum256([]byte(text))
	return hex.EncodeToString(sum[:])
}

// Sha256File returns the SHA-256 of the bytes of the file at path, as
// lowercase hex. io.Copy reads the file in chunks, so a large file does not
// fill the memory.
func Sha256File(path string) (string, error) {
	f, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer f.Close()
	h := sha256.New()
	if _, err := io.Copy(h, f); err != nil {
		return "", err
	}
	return hex.EncodeToString(h.Sum(nil)), nil
}
sha256_hash_test.go 82 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

package sha256hash

import (
	"bytes"
	"errors"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

var textCases = []struct {
	name, text, want string
}{
	{"abc", "abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"},
	{"two-block-56", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"},
	{"fox", "The quick brown fox jumps over the lazy dog", "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"},
	{"empty", "", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"},
	{"a-55", strings.Repeat("a", 55), "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318"},
	{"a-56", strings.Repeat("a", 56), "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a"},
	{"a-63", strings.Repeat("a", 63), "7d3e74a05d7db15bce4ad9ec0658ea98e3f06eeecf16b4c6fff2da457ddc2f34"},
	{"a-64", strings.Repeat("a", 64), "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb"},
	{"multi-block-112", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1"},
	{"non-ascii", "naïve café 日本語 \U0001F642", "9c53e090acd67abd65c64ee431a36bdc36c3fd86341f5814a94d1b901ca9ed8d"},
	{"nfc-cafe", "caf\u00e9", "850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e"},
	{"nfd-cafe", "cafe\u0301", "81ef060bcd98adc7824eb5c1ada83c32491b16018e11e79f00ab9d09e04b015a"},
	{"trailing-newline", "abc\n", "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"},
}

// From cases/files.jsonl.
var fileCases = []struct {
	name string
	data []byte
	want string
}{
	{"abc-file", []byte("abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"},
	{"abc-newline-file", []byte("abc\n"), "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb"},
	{"abc-crlf-file", []byte("abc\r\n"), "552bab6864c7a7b69a502ed1854b9245c0e1a30f008aaa0b281da62585fdb025"},
	{"empty-file", []byte{}, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"},
	{"binary-file", []byte{0x00, 0x01, 0xff}, "26a66b061e8f48f39927c312f25293959729eee95978e2892d49d3512a5cc092"},
	// One million repetitions of "a": more than one chunk.
	{"million-a-file", bytes.Repeat([]byte("a"), 1_000_000), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"},
}

func TestSha256Text(t *testing.T) {
	for _, c := range textCases {
		t.Run(c.name, func(t *testing.T) {
			if got := Sha256Text(c.text); got != c.want {
				t.Errorf("got %s, want %s", got, c.want)
			}
		})
	}
}

func TestSha256File(t *testing.T) {
	for _, c := range fileCases {
		t.Run(c.name, func(t *testing.T) {
			path := filepath.Join(t.TempDir(), "in.bin")
			if err := os.WriteFile(path, c.data, 0o644); err != nil {
				t.Fatal(err)
			}
			got, err := Sha256File(path)
			if err != nil {
				t.Fatal(err)
			}
			if got != c.want {
				t.Errorf("got %s, want %s", got, c.want)
			}
		})
	}
}

func TestMissingFile(t *testing.T) {
	_, err := Sha256File(filepath.Join(t.TempDir(), "missing.txt"))
	if !errors.Is(err, fs.ErrNotExist) {
		t.Errorf("got error %v, want fs.ErrNotExist", err)
	}
}
sha256_hash.rsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

//! SHA-256 as FIPS 180-4 defines it. The Rust standard library has no
//! SHA-256, so this file holds a short implementation.

use std::fs::File;
use std::io::{self, Read};
use std::path::Path;

// FIPS 180-4, 4.2.2: the first 32 bits of the fractional parts of the cube
// roots of the first 64 primes.
const K: [u32; 64] = [
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];

// FIPS 180-4, 5.3.3: the initial hash value.
const H0: [u32; 8] = [
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
];

/// A SHA-256 computation that takes the message in parts.
#[derive(Clone)]
pub struct Sha256 {
    state: [u32; 8],
    block: [u8; 64],
    used: usize,
    // The length of the message in bytes. FIPS 180-4 allows fewer than 2^64 bits.
    len: u64,
}

impl Default for Sha256 {
    fn default() -> Self {
        Self::new()
    }
}

impl Sha256 {
    pub fn new() -> Sha256 {
        Sha256 {
            state: H0,
            block: [0; 64],
            used: 0,
            len: 0,
        }
    }

    /// Adds the bytes of data to the message.
    pub fn update(&mut self, mut data: &[u8]) {
        self.len = self.len.wrapping_add(data.len() as u64);
        while !data.is_empty() {
            let n = (64 - self.used).min(data.len());
            self.block[self.used..self.used + n].copy_from_slice(&data[..n]);
            self.used += n;
            data = &data[n..];
            if self.used == 64 {
                compress(&mut self.state, &self.block);
                self.used = 0;
            }
        }
    }

    /// Pads the message and returns the 32-byte digest.
    pub fn finalize(mut self) -> [u8; 32] {
        // FIPS 180-4, 5.1.1: a 1 bit, then zero bits, then the length in bits
        // as a 64-bit big-endian number, to a multiple of 512 bits.
        let bits = self.len.wrapping_mul(8);
        self.block[self.used] = 0x80;
        self.block[self.used + 1..].fill(0);
        if self.used >= 56 {
            // No room for the length: it goes in one more block.
            compress(&mut self.state, &self.block);
            self.block = [0; 64];
        }
        self.block[56..].copy_from_slice(&bits.to_be_bytes());
        compress(&mut self.state, &self.block);
        let mut out = [0u8; 32];
        for (chunk, word) in out.chunks_exact_mut(4).zip(self.state) {
            chunk.copy_from_slice(&word.to_be_bytes());
        }
        out
    }
}

// FIPS 180-4, 6.2.2: the hash computation for one 512-bit block.
fn compress(state: &mut [u32; 8], block: &[u8; 64]) {
    let mut w = [0u32; 64];
    for (t, word) in block.chunks_exact(4).enumerate() {
        w[t] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
    }
    for t in 16..64 {
        let s0 = w[t - 15].rotate_right(7) ^ w[t - 15].rotate_right(18) ^ (w[t - 15] >> 3);
        let s1 = w[t - 2].rotate_right(17) ^ w[t - 2].rotate_right(19) ^ (w[t - 2] >> 10);
        w[t] = s1
            .wrapping_add(w[t - 7])
            .wrapping_add(s0)
            .wrapping_add(w[t - 16]);
    }
    let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *state;
    for t in 0..64 {
        let big_s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
        let ch = (e & f) ^ (!e & g);
        let t1 = h
            .wrapping_add(big_s1)
            .wrapping_add(ch)
            .wrapping_add(K[t])
            .wrapping_add(w[t]);
        let big_s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
        let maj = (a & b) ^ (a & c) ^ (b & c);
        let t2 = big_s0.wrapping_add(maj);
        h = g;
        g = f;
        f = e;
        e = d.wrapping_add(t1);
        d = c;
        c = b;
        b = a;
        a = t1.wrapping_add(t2);
    }
    for (s, v) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) {
        *s = s.wrapping_add(v);
    }
}

/// Returns the digest as 64 lowercase hexadecimal digits.
pub fn to_hex(digest: &[u8; 32]) -> String {
    // {:02x} keeps the leading zero of each byte.
    digest.iter().map(|b| format!("{b:02x}")).collect()
}

/// Returns the SHA-256 of the bytes of data, as lowercase hex.
pub fn sha256_hex(data: &[u8]) -> String {
    let mut h = Sha256::new();
    h.update(data);
    to_hex(&h.finalize())
}

/// Returns the SHA-256 of the UTF-8 bytes of text, as lowercase hex.
/// A Rust str is always UTF-8, so its bytes are the encoding.
pub fn sha256_text(text: &str) -> String {
    sha256_hex(text.as_bytes())
}

/// Returns the SHA-256 of the bytes of the file at path, as lowercase hex.
/// The file is read in chunks, so a large file does not fill the memory.
pub fn sha256_file(path: impl AsRef<Path>) -> io::Result<String> {
    let mut file = File::open(path)?;
    let mut h = Sha256::new();
    let mut buf = [0u8; 8192];
    loop {
        match file.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => h.update(&buf[..n]),
            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
            Err(e) => return Err(e),
        }
    }
    Ok(to_hex(&h.finalize()))
}
tests/sha256_hash_test.rs 254 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

use algo_compute_a_sha_256_hash::{Sha256, sha256_file, sha256_hex, sha256_text, to_hex};
use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};

// A new empty directory for one test, removed when it goes out of scope.
struct TempDir(PathBuf);

impl TempDir {
    fn new() -> TempDir {
        static COUNT: AtomicU64 = AtomicU64::new(0);
        let n = COUNT.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!("sha256-{}-{n}", std::process::id()));
        fs::create_dir(&dir).unwrap();
        TempDir(dir)
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

fn text_cases() -> Vec<(&'static str, String, &'static str)> {
    let a = |n| "a".repeat(n);
    vec![
        (
            "abc",
            "abc".into(),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
        ),
        (
            "two-block-56",
            "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".into(),
            "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
        ),
        (
            "fox",
            "The quick brown fox jumps over the lazy dog".into(),
            "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592",
        ),
        (
            "empty",
            "".into(),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        ),
        (
            "a-55",
            a(55),
            "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318",
        ),
        (
            "a-56",
            a(56),
            "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a",
        ),
        (
            "a-63",
            a(63),
            "7d3e74a05d7db15bce4ad9ec0658ea98e3f06eeecf16b4c6fff2da457ddc2f34",
        ),
        (
            "a-64",
            a(64),
            "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb",
        ),
        (
            "multi-block-112",
            concat!(
                "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn",
                "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"
            )
            .into(),
            "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1",
        ),
        (
            "non-ascii",
            "na\u{ef}ve caf\u{e9} \u{65e5}\u{672c}\u{8a9e} \u{1f642}".into(),
            "9c53e090acd67abd65c64ee431a36bdc36c3fd86341f5814a94d1b901ca9ed8d",
        ),
        (
            "nfc-cafe",
            "caf\u{e9}".into(),
            "850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e",
        ),
        (
            "nfd-cafe",
            "cafe\u{301}".into(),
            "81ef060bcd98adc7824eb5c1ada83c32491b16018e11e79f00ab9d09e04b015a",
        ),
        (
            "trailing-newline",
            "abc\n".into(),
            "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb",
        ),
    ]
}

// From cases/files.jsonl.
fn file_cases() -> Vec<(&'static str, Vec<u8>, &'static str)> {
    vec![
        (
            "abc-file",
            b"abc".to_vec(),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
        ),
        (
            "abc-newline-file",
            b"abc\n".to_vec(),
            "edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb",
        ),
        (
            "abc-crlf-file",
            b"abc\r\n".to_vec(),
            "552bab6864c7a7b69a502ed1854b9245c0e1a30f008aaa0b281da62585fdb025",
        ),
        (
            "empty-file",
            vec![],
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        ),
        (
            "binary-file",
            vec![0x00, 0x01, 0xff],
            "26a66b061e8f48f39927c312f25293959729eee95978e2892d49d3512a5cc092",
        ),
        // One million repetitions of "a": more than one chunk.
        (
            "million-a-file",
            vec![b'a'; 1_000_000],
            "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0",
        ),
    ]
}

// The SHA-256 Test Data of the NIST example values, SHA2_Additional.pdf.
fn nist_cases() -> Vec<(&'static str, Vec<u8>, &'static str)> {
    vec![
        (
            "nist-1",
            vec![0xbd],
            "68325720aabd7c82f30f554b313d0570c95accbb7dc4b5aae11204c08ffe732b",
        ),
        (
            "nist-2",
            vec![0xc9, 0x8c, 0x8e, 0x55],
            "7abc22c0ae5af26ce93dbb94433a0e0b2e119d014f8e7f65bd56c61ccccd9504",
        ),
        (
            "nist-3",
            vec![0; 55],
            "02779466cdec163811d078815c633f21901413081449002f24aa3e80f0b88ef7",
        ),
        (
            "nist-4",
            vec![0; 56],
            "d4817aa5497628e7c77e6b606107042bbba3130888c5f47a375e6179be789fbb",
        ),
        (
            "nist-5",
            vec![0; 57],
            "65a16cb7861335d5ace3c60718b5052e44660726da4cd13bb745381b235a1785",
        ),
        (
            "nist-6",
            vec![0; 64],
            "f5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b",
        ),
        (
            "nist-7",
            vec![0; 1000],
            "541b3e9daa09b20bf85fa273e5cbd3e80185aa4ec298e765db87742b70138a53",
        ),
        (
            "nist-8",
            vec![b'A'; 1000],
            "c2e686823489ced2017f6059b8b239318b6364f6dcd835d0a519105a1eadd6e4",
        ),
        (
            "nist-9",
            vec![b'U'; 1005],
            "f4d62ddec0f3dd90ea1380fa16a5ff8dc4c54b21740650f24afc4120903552b0",
        ),
        (
            "nist-10",
            vec![0; 1_000_000],
            "d29751f2649b32ff572b5e0a9f541ea660a50f94ff0beedfb0b692b924cc8025",
        ),
    ]
}

#[test]
fn text() {
    for (name, text, want) in text_cases() {
        assert_eq!(sha256_text(&text), want, "{name}");
    }
}

#[test]
fn file() {
    let dir = TempDir::new();
    let path = dir.0.join("in.bin");
    for (name, data, want) in file_cases() {
        fs::write(&path, &data).unwrap();
        assert_eq!(sha256_file(&path).unwrap(), want, "{name}");
    }
}

#[test]
fn missing_file() {
    let dir = TempDir::new();
    let err = sha256_file(dir.0.join("missing.txt")).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}

#[test]
fn nist() {
    for (name, data, want) in nist_cases() {
        assert_eq!(sha256_hex(&data), want, "{name}");
    }
}

// The message in parts of 1, 2, ..., 130 bytes gives the same digest as in one part.
#[test]
fn update_in_parts() {
    let data: Vec<u8> = (0..1000u32).map(|i| (i % 251) as u8).collect();
    let want = sha256_hex(&data);
    for size in 1..=130 {
        let mut h = Sha256::new();
        for part in data.chunks(size) {
            h.update(part);
        }
        assert_eq!(to_hex(&h.finalize()), want, "parts of {size}");
    }
}

// One million repetitions of "a", in parts of 1000 bytes.
#[test]
fn million_a() {
    let mut h = Sha256::new();
    let part = [b'a'; 1000];
    for _ in 0..1000 {
        h.update(&part);
    }
    assert_eq!(
        to_hex(&h.finalize()),
        "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"
    );
}
sha256_hash.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

# Bash has no SHA-256 of its own. These functions call sha256sum from GNU
# coreutils. It prints the digest, then the name of the input. The functions
# keep the text before the first space.

# sha256_text TEXT prints the SHA-256 of the bytes of TEXT, as they are. For
# the contract, TEXT holds UTF-8 bytes.
sha256_text() {
  local out
  # printf '%s' writes the bytes with no newline at the end. echo adds one.
  out=$(printf '%s' "$1" | sha256sum) || return
  printf '%s\n' "${out%% *}"
}

# sha256_file PATH prints the SHA-256 of the bytes of the file at PATH.
# sha256sum reads the file from the standard input, so the name in its output
# is "-" and does not depend on PATH.
sha256_file() {
  local out
  out=$(sha256sum <"$1") || return
  printf '%s\n' "${out%% *}"
}
test_sha256_hash.bats 61 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-a-sha-256-hash/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/sha256_hash.sh"
  file="$BATS_TEST_TMPDIR/in.bin"
}

check_text() { # check_text TEXT WANT
  run sha256_text "$1"
  [ "$status" -eq 0 ]
  [ "$output" = "$2" ]
}

# repeat CHAR N prints N copies of CHAR.
repeat() { printf "%$2s" '' | tr ' ' "$1"; }

@test "abc" { check_text abc ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad; }
@test "two-block-56" { check_text abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq 248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1; }
@test "fox" { check_text 'The quick brown fox jumps over the lazy dog' d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592; }
@test "empty" { check_text '' e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855; }
@test "a-55" { check_text "$(repeat a 55)" 9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318; }
@test "a-56" { check_text "$(repeat a 56)" b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a; }
@test "a-63" { check_text "$(repeat a 63)" 7d3e74a05d7db15bce4ad9ec0658ea98e3f06eeecf16b4c6fff2da457ddc2f34; }
@test "a-64" { check_text "$(repeat a 64)" ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb; }
@test "multi-block-112" { check_text abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1; }
@test "non-ascii" { check_text $'na\xc3\xafve caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e \xf0\x9f\x99\x82' 9c53e090acd67abd65c64ee431a36bdc36c3fd86341f5814a94d1b901ca9ed8d; }
@test "nfc-cafe" { check_text $'caf\xc3\xa9' 850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e; }
@test "nfd-cafe" { check_text $'cafe\xcc\x81' 81ef060bcd98adc7824eb5c1ada83c32491b16018e11e79f00ab9d09e04b015a; }
@test "trailing-newline" { check_text $'abc\n' edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb; }

check_file() { # check_file BYTES WANT; BYTES is a printf %b string
  printf '%b' "$1" >"$file"
  run sha256_file "$file"
  [ "$status" -eq 0 ]
  [ "$output" = "$2" ]
}

# The cases of cases/files.jsonl.
@test "abc-file" { check_file 'abc' ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad; }
@test "abc-newline-file" { check_file 'abc\n' edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb; }
@test "abc-crlf-file" { check_file 'abc\r\n' 552bab6864c7a7b69a502ed1854b9245c0e1a30f008aaa0b281da62585fdb025; }
@test "empty-file" { check_file '' e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855; }
@test "binary-file" { check_file '\0000\0001\0377' 26a66b061e8f48f39927c312f25293959729eee95978e2892d49d3512a5cc092; }

# One million repetitions of "a".
@test "million-a-file" {
  repeat a 1000000 >"$file"
  run sha256_file "$file"
  [ "$status" -eq 0 ]
  [ "$output" = cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0 ]
}

@test "missing-file" {
  run --separate-stderr sha256_file "$BATS_TEST_TMPDIR/missing.txt"
  [ "$status" -ne 0 ]
  [ -z "$output" ]
}

References

  1. NIST, FIPS PUB 180-4, Secure Hash Standard (SHS), Announcement item 3 (Explanation); 4.2.2 SHA-224 and SHA-256 Constants; 5.1.1 SHA-1, SHA-224 and SHA-256 (padding); 5.3.3 SHA-256 (initial hash value); 6.2.2 SHA-256 Hash Computation
  2. NIST, Cryptographic Standards and Guidelines, Example Values, SHA-256, One Block Message Sample; Two Block Message Sample
  3. NIST, Cryptographic Standards and Guidelines, Example Values, SHA-2 additional test data, SHA-256 Test Data,
  4. NIST SP 800-63B-4, Digital Identity Guidelines, Authentication and Authenticator Management, 3.1.1.2 Password Verifiers
  5. The Python Standard Library, hashlib, hashlib.file_digest, hash.hexdigest, Key derivation
  6. The Python Standard Library, hmac, hmac.compare_digest
  7. The Python Standard Library, unicodedata, unicodedata.normalize
  8. Node.js documentation, Crypto, Class Hash, hash.update(data[, inputEncoding]), hash.digest([encoding])
  9. Java SE 25 API, java.security.MessageDigest, class description (required algorithms), digest(byte[])
  10. Java SE 25 API, java.util.HexFormat, of(), formatHex(byte[])
  11. .NET API reference, SHA256.HashData, HashData(Byte[]), HashData(Stream)
  12. .NET API reference, Convert.ToHexString, ToHexString(Byte[]), Returns
  13. .NET API reference, Convert.ToHexStringLower, ToHexStringLower(Byte[])
  14. .NET API reference, Encoding.Unicode, Property Value
  15. Go standard library, package crypto/sha256, package overview, Sum256, New
  16. Linux man-pages, sha256sum(1), Description

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (cpp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (csharp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (go)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (java)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (javascript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (python)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (rust)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (typescript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source

The native tests pass in 9 of 10 languages in this build.