6 n__sha256_8h
gullradriel edited this page 2026-10-09 00:55:18 +02:00

include/nilorea/n_sha256.h

SHA-256 in portable C, fed a piece at a time. More...

Structures

Name
struct N_SHA256
a SHA-256 in progress: plain data, copyable to fork a hash

Detailed Description

SHA-256 in portable C, fed a piece at a time.

Author: Castagnier Mickael

Version: 1.0

Date: 28/09/2026

FIPS 180-4 SHA-256 with no library behind it, for a program that must check a download or a cache entry without linking OpenSSL (n_digest.h is the OpenSSL one, one call per buffer). The state is fed any number of pieces of any size, so a file of any length is hashed in constant memory; n_sha256_file() does that for a path. Hex output is lowercase, the form published beside downloads.

Source code

/*
 * Nilorea Library
 * Copyright (C) 2005-2026 Castagnier Mickael
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 */


#ifndef __NILOREA_SHA256__
#define __NILOREA_SHA256__

#ifdef __cplusplus
extern "C" {
#endif


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

#define N_SHA256_LEN 32
#define N_SHA256_HEX_LEN 65

typedef struct N_SHA256 {
    uint32_t state[8];
    uint64_t length;
    unsigned char block[64];
    size_t used;
} N_SHA256;

void n_sha256_init(N_SHA256* ctx);

void n_sha256_update(N_SHA256* ctx, const void* data, size_t len);

void n_sha256_final(N_SHA256* ctx, unsigned char out[N_SHA256_LEN]);

void n_sha256(const void* data, size_t len, unsigned char out[N_SHA256_LEN]);

int n_sha256_file(const char* path, unsigned char out[N_SHA256_LEN]);

void n_sha256_hex(const unsigned char digest[N_SHA256_LEN], char out[N_SHA256_HEX_LEN]);


#ifdef __cplusplus
}
#endif

#endif /* __NILOREA_SHA256__ */