nanosha256 - Technical Manual

Generated on: 2026-04-01


nanosha256 Documentation Overview

Welcome to thenanosha256documentation. This library is a high-performance, memory-safe, single-header C implementation of the SHA-256 cryptographic hash algorithm.

Key Features

Quick Start

Include the header in your project:

#include "nanosha256.h"

API Reference

Thenanosha256library provides two distinct APIs: a high-levelStreaming API(using a context struct) and a low-levelState-based API(primitives).


1. Streaming API (Recommended)

This API manages a message of arbitrary length by buffering blocks.

SHA256_Init(SHA256_CTX *ctx)

Initializes the context for hashing.

SHA256_Update(SHA256_CTX *ctx, const void *data, size_t len)

Processes a chunk of data. Can be called multiple times.

SHA256_Final(uint8_t hash[32], SHA256_CTX *ctx)

Finalizes the hash calculation, produces the 32-byte digest, andsecurely wipesthe context.


2. Low-Level Primitives

These functions operate directly on states and 64-byte blocks.

sha256_init(uint32_t state[8])

Sets the 8 initial 32-bit words to the FIPS 180-4 constants.

sha256_transform(uint32_t state[8], const uint8_t data[64])

Performs the 64 compression rounds on a single 512-bit block.

sha256_final(uint32_t state[8], uint8_t hash[32], uint64_t total_bits)

Converts the final internal 32-bit state words into a Big-Endian byte array.


Security and Memory Safety

nanosha256is designed to avoid common pitfalls in systems programming while maintaining cryptographic speed.

1. NULL Pointer Protection

All public API functions test forNULLbefore dereferencing any parameters (ctx,data, orhash). This prevents crashes in the event of logical errors in the caller.

2. Integer Overflow Guard

SHA256_Updateimplements an overflow check for the total message length (ctx->total_len). If adding a chunk's length to the existing count exceeds 64 bits, the function returns-2to prevent wrapping and incorrect hashing.

3. Strict Buffer Boundary Tracking

Thectx->buffer(64 bytes) is used for residual data between large block transformations. Eachmemcpyis calculated against the remaining space (64 - left) to ensure no out-of-bounds writes occur.

4. Secure Cleanup

After the 32-byte digest is generated inSHA256_Final, the context struct — including the internal state and the residue buffer — is zeroed usingmemset(ctx, 0, sizeof(SHA256_CTX))to prevent sensitive hash fragments from leaking into memory.

5. Alignment-Safe Byte Loading

The library avoids direct pointer casting touint32_t*, which can cause alignment or bus errors on certain architectures. All transfers usememcpyfor portable, safe byte-to-word conversions.