Add SHA-256 checksum calculation support

This commit is contained in:
2025-10-03 02:03:39 +01:00
parent 1e569c68a1
commit 79ac2e380c
10 changed files with 329 additions and 124 deletions

View File

@@ -129,7 +129,9 @@ add_library(aaruformat SHARED include/aaruformat/consts.h include/aaruformat/enu
src/md5.c src/md5.c
include/md5.h include/md5.h
src/sha1.c src/sha1.c
include/sha1.h) include/sha1.h
src/sha256.c
include/sha256.h)
include_directories(include include/aaruformat 3rdparty/uthash/include 3rdparty/uthash/src) include_directories(include include/aaruformat 3rdparty/uthash/include 3rdparty/uthash/src)
@@ -161,34 +163,6 @@ endif()
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake-modules") list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake-modules")
# include(FindLibreSSL.cmake)
# Check for OpenSSL and SHA256_Init
find_package(OpenSSL QUIET)
find_package(LibreSSL QUIET)
include(CheckFunctionExists)
set(CMAKE_REQUIRED_LIBRARIES OpenSSL::Crypto)
check_function_exists(SHA256_Init HAVE_OPENSSL_SHA256_INIT)
if(OpenSSL_FOUND)
message("-- OpenSSL VERSION: ${OPENSSL_VERSION}")
endif()
if(LIBRESSL_FOUND)
message("-- LibreSSL VERSION: ${LIBRESSL_VERSION}")
endif()
if((OpenSSL_FOUND OR LIBRESSL_FOUND) AND HAVE_OPENSSL_SHA256_INIT)
add_compile_definitions(AARU_HAS_SHA256)
endif()
if(LIBRESSL_FOUND)
TARGET_LINK_LIBRARIES_WHOLE_ARCHIVE(aaruformat ${LIBRESSL_CRYPTO_LIBRARY})
elif(OpenSSL_FOUND)
TARGET_LINK_LIBRARIES_WHOLE_ARCHIVE(aaruformat ${OPENSSL_CRYPTO_LIBRARY})
endif()
set(CMAKE_POSITION_INDEPENDENT_CODE ON) set(CMAKE_POSITION_INDEPENDENT_CODE ON)
# Add slog submodule # Add slog submodule

View File

@@ -24,6 +24,7 @@
#include "lru.h" #include "lru.h"
#include "md5.h" #include "md5.h"
#include "sha1.h" #include "sha1.h"
#include "sha256.h"
#include "structs.h" #include "structs.h"
#include "utarray.h" #include "utarray.h"
@@ -212,12 +213,14 @@ typedef struct aaruformatContext
hash_map_t *sectorHashMap; ///< Deduplication hash map (fingerprint->entry mapping). hash_map_t *sectorHashMap; ///< Deduplication hash map (fingerprint->entry mapping).
bool deduplicate; ///< Storage deduplication active (duplicates coalesce). bool deduplicate; ///< Storage deduplication active (duplicates coalesce).
bool rewinded; ///< True if stream has been rewound after open (write path). bool rewinded; ///< True if stream has been rewound after open (write path).
uint64_t last_written_block; ///< Last written block number (write path). uint64_t last_written_block; ///< Last written block number (write path).
bool calculating_md5; ///< True if whole-image MD5 being calculated on-the-fly. bool calculating_md5; ///< True if whole-image MD5 being calculated on-the-fly.
md5_ctx md5_context; ///< Opaque MD5 context for streaming updates md5_ctx md5_context; ///< Opaque MD5 context for streaming updates
bool calculating_sha1; ///< True if whole-image SHA-1 being calculated on-the-fly. bool calculating_sha1; ///< True if whole-image SHA-1 being calculated on-the-fly.
sha1_ctx sha1_context; ///< Opaque SHA-1 context for streaming updates sha1_ctx sha1_context; ///< Opaque SHA-1 context for streaming updates
bool calculating_sha256; ///< True if whole-image SHA-256 being calculated on-the-fly.
sha256_ctx sha256_context; ///< Opaque SHA-256 context for streaming updates
} aaruformatContext; } aaruformatContext;
/** \struct DumpHardwareEntriesWithData /** \struct DumpHardwareEntriesWithData

View File

@@ -22,6 +22,7 @@
#include "crc64.h" #include "crc64.h"
#include "md5.h" #include "md5.h"
#include "sha1.h" #include "sha1.h"
#include "sha256.h"
#include "simd.h" #include "simd.h"
#include "spamsum.h" #include "spamsum.h"
#ifdef __cplusplus #ifdef __cplusplus
@@ -169,6 +170,11 @@ AARU_EXPORT void AARU_CALL aaruf_sha1_update(sha1_ctx *ctx, const void *data, un
AARU_EXPORT void AARU_CALL aaruf_sha1_final(sha1_ctx *ctx, unsigned char *result); AARU_EXPORT void AARU_CALL aaruf_sha1_final(sha1_ctx *ctx, unsigned char *result);
AARU_EXPORT void AARU_CALL aaruf_sha1_buffer(const void *data, unsigned long size, unsigned char *result); AARU_EXPORT void AARU_CALL aaruf_sha1_buffer(const void *data, unsigned long size, unsigned char *result);
AARU_EXPORT void AARU_CALL aaruf_sha256_init(sha256_ctx *ctx);
AARU_EXPORT void AARU_CALL aaruf_sha256_update(sha256_ctx *ctx, const void *data, unsigned long size);
AARU_EXPORT void AARU_CALL aaruf_sha256_final(sha256_ctx *ctx, unsigned char *result);
AARU_EXPORT void AARU_CALL aaruf_sha256_buffer(const void *data, unsigned long size, unsigned char *result);
#if defined(__x86_64__) || defined(__amd64) || defined(_M_AMD64) || defined(_M_X64) || defined(__I386__) || \ #if defined(__x86_64__) || defined(__amd64) || defined(_M_AMD64) || defined(_M_X64) || defined(__I386__) || \
defined(__i386__) || defined(__THW_INTEL) || defined(_M_IX86) defined(__i386__) || defined(__THW_INTEL) || defined(_M_IX86)

52
include/sha256.h Normal file
View File

@@ -0,0 +1,52 @@
/*
* Public domain / MIT SHA-256 implementation for libaaruformat.
*
* This code is released into the public domain. If that is not recognized
* in your jurisdiction, you may instead treat it under the terms of the
* MIT license reproduced below.
*
* MIT License
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef LIBAARUFORMAT_SHA256_H
#define LIBAARUFORMAT_SHA256_H
#include <stdint.h>
#ifdef __cplusplus
extern "C"
{
#endif
#ifndef SHA256_DIGEST_LENGTH
#define SHA256_DIGEST_LENGTH 32
#endif
typedef struct
{
uint32_t state[8];
uint64_t bitcount; /* total bits processed */
uint8_t buffer[64];
} sha256_ctx;
#ifdef __cplusplus
}
#endif
#endif /* LIBAARUFORMAT_SHA256_H */

View File

@@ -511,6 +511,11 @@ int aaruf_close(void *context)
ctx->checksums.hasSha1 = true; ctx->checksums.hasSha1 = true;
aaruf_sha1_final(&ctx->sha1_context, ctx->checksums.sha1); aaruf_sha1_final(&ctx->sha1_context, ctx->checksums.sha1);
} }
if(ctx->calculating_sha256)
{
ctx->checksums.hasSha256 = true;
aaruf_sha256_final(&ctx->sha256_context, ctx->checksums.sha256);
}
// Write the checksums block // Write the checksums block
bool has_checksums = bool has_checksums =

View File

@@ -320,6 +320,11 @@ void *aaruf_create(const char *filepath, const uint32_t media_type, const uint32
ctx->calculating_sha1 = true; ctx->calculating_sha1 = true;
aaruf_sha1_init(&ctx->sha1_context); aaruf_sha1_init(&ctx->sha1_context);
} }
if(parsed_options.sha256)
{
ctx->calculating_sha256 = true;
aaruf_sha256_init(&ctx->sha256_context);
}
// Is writing // Is writing
ctx->isWriting = true; ctx->isWriting = true;

147
src/sha256.c Normal file
View File

@@ -0,0 +1,147 @@
/*
* Public domain / MIT SHA-256 implementation for libaaruformat.
*
* Reference: FIPS PUB 180-4.
*/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "decls.h"
#include "sha256.h"
#ifndef AARU_LOCAL
#define AARU_LOCAL static
#endif
#if defined(_MSC_VER)
#define ROTR32(x, n) _rotr((x), (n))
#else
#define ROTR32(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
#endif
#define Ch(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
#define Maj(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#define SIGMA0(x) (ROTR32((x), 2) ^ ROTR32((x), 13) ^ ROTR32((x), 22))
#define SIGMA1(x) (ROTR32((x), 6) ^ ROTR32((x), 11) ^ ROTR32((x), 25))
#define sigma0(x) (ROTR32((x), 7) ^ ROTR32((x), 18) ^ ((x) >> 3))
#define sigma1(x) (ROTR32((x), 17) ^ ROTR32((x), 19) ^ ((x) >> 10))
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};
AARU_LOCAL void sha256_transform(uint32_t state[8], const uint8_t block[64])
{
uint32_t W[64];
for(int i = 0; i < 16; i++)
W[i] = ((uint32_t)block[i * 4] << 24) | ((uint32_t)block[i * 4 + 1] << 16) | ((uint32_t)block[i * 4 + 2] << 8) |
(uint32_t)block[i * 4 + 3];
for(int i = 16; i < 64; i++) W[i] = sigma1(W[i - 2]) + W[i - 7] + sigma0(W[i - 15]) + W[i - 16];
uint32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4], f = state[5], g = state[6],
h = state[7];
for(int i = 0; i < 64; i++)
{
uint32_t T1 = h + SIGMA1(e) + Ch(e, f, g) + K[i] + W[i];
uint32_t T2 = SIGMA0(a) + Maj(a, 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;
}
AARU_EXPORT void AARU_CALL aaruf_sha256_init(sha256_ctx *ctx)
{
ctx->state[0] = 0x6a09e667U;
ctx->state[1] = 0xbb67ae85U;
ctx->state[2] = 0x3c6ef372U;
ctx->state[3] = 0xa54ff53aU;
ctx->state[4] = 0x510e527fU;
ctx->state[5] = 0x9b05688cU;
ctx->state[6] = 0x1f83d9abU;
ctx->state[7] = 0x5be0cd19U;
ctx->bitcount = 0ULL;
memset(ctx->buffer, 0, sizeof(ctx->buffer));
}
AARU_EXPORT void AARU_CALL aaruf_sha256_update(sha256_ctx *ctx, const void *data_ptr, unsigned long len)
{
if(len == 0) return;
const uint8_t *data = (const uint8_t *)data_ptr;
uint32_t idx = (uint32_t)((ctx->bitcount >> 3) & 0x3F);
ctx->bitcount += ((uint64_t)len) << 3;
uint32_t space = 64 - idx;
if(len >= space)
{
memcpy(ctx->buffer + idx, data, space);
sha256_transform(ctx->state, ctx->buffer);
data += space;
len -= space;
while(len >= 64)
{
sha256_transform(ctx->state, data);
data += 64;
len -= 64;
}
idx = 0;
}
if(len > 0) memcpy(ctx->buffer + idx, data, len);
}
AARU_EXPORT void AARU_CALL aaruf_sha256_final(sha256_ctx *ctx, unsigned char *out)
{
uint8_t pad[64];
memset(pad, 0, sizeof(pad));
pad[0] = 0x80;
uint8_t len_be[8];
uint64_t bits = ctx->bitcount;
for(int i = 0; i < 8; i++) len_be[7 - i] = (uint8_t)(bits >> (i * 8));
uint32_t idx = (uint32_t)((ctx->bitcount >> 3) & 0x3F);
uint32_t pad_len = (idx < 56) ? (56 - idx) : (120 - idx);
aaruf_sha256_update(ctx, pad, pad_len);
aaruf_sha256_update(ctx, len_be, 8);
for(int i = 0; i < 8; i++)
{
out[i * 4] = (uint8_t)(ctx->state[i] >> 24);
out[i * 4 + 1] = (uint8_t)(ctx->state[i] >> 16);
out[i * 4 + 2] = (uint8_t)(ctx->state[i] >> 8);
out[i * 4 + 3] = (uint8_t)(ctx->state[i]);
}
memset(ctx->buffer, 0, sizeof(ctx->buffer));
}
AARU_EXPORT void AARU_CALL aaruf_sha256_buffer(const void *data, unsigned long size, unsigned char *result)
{
sha256_ctx ctx;
aaruf_sha256_init(&ctx);
aaruf_sha256_update(&ctx, data, size);
aaruf_sha256_final(&ctx, result);
}

View File

@@ -156,6 +156,8 @@ int32_t aaruf_write_sector(void *context, uint64_t sector_address, bool negative
if(ctx->calculating_md5) ctx->calculating_md5 = false; if(ctx->calculating_md5) ctx->calculating_md5 = false;
// Disable SHA1 calculation // Disable SHA1 calculation
if(ctx->calculating_sha1) ctx->calculating_sha1 = false; if(ctx->calculating_sha1) ctx->calculating_sha1 = false;
// Disable SHA256 calculation
if(ctx->calculating_sha256) ctx->calculating_sha256 = false;
} }
else else
ctx->last_written_block = sector_address; ctx->last_written_block = sector_address;
@@ -167,6 +169,9 @@ int32_t aaruf_write_sector(void *context, uint64_t sector_address, bool negative
// Calculate SHA1 on-the-fly if requested and sector is within user sectors (not negative or overflow) // Calculate SHA1 on-the-fly if requested and sector is within user sectors (not negative or overflow)
if(ctx->calculating_sha1 && !negative && sector_address <= ctx->imageInfo.Sectors) if(ctx->calculating_sha1 && !negative && sector_address <= ctx->imageInfo.Sectors)
aaruf_sha1_update(&ctx->sha1_context, data, length); aaruf_sha1_update(&ctx->sha1_context, data, length);
// Calculate SHA256 on-the-fly if requested and sector is within user sectors (not negative or overflow)
if(ctx->calculating_sha256 && !negative && sector_address <= ctx->imageInfo.Sectors)
aaruf_sha256_update(&ctx->sha256_context, data, length);
// TODO: If optical disc check track // TODO: If optical disc check track

View File

@@ -7,36 +7,15 @@ project(tests)
add_subdirectory(lib) add_subdirectory(lib)
include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR} ../include ../3rdparty/uthash/include ../3rdparty/uthash/src) include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR} ../include ../3rdparty/uthash/include ../3rdparty/uthash/src)
# Find OpenSSL for tests that use it directly # Copy test data files into build tree
find_package(OpenSSL QUIET) file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/data/random DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/data/)
find_package(LibreSSL QUIET) file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/data/flac.flac DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/data/)
file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/data/audio.bin DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/data/)
file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/data/lzma.bin DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/data/)
file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/data/data.bin DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/data/)
file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/data/random # Test executable (all unit tests)
DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/data/)
file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/data/flac.flac
DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/data/)
file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/data/audio.bin
DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/data/)
file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/data/lzma.bin
DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/data/)
file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/data/data.bin
DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/data/)
# 'Google_Tests_run' is the target name
# 'test1.cpp tests2.cpp' are source files with tests
add_executable(tests_run crc64.cpp spamsum.cpp crc32.c crc32.h flac.cpp lzma.cpp sha256.cpp md5.cpp sha1.cpp) add_executable(tests_run crc64.cpp spamsum.cpp crc32.c crc32.h flac.cpp lzma.cpp sha256.cpp md5.cpp sha1.cpp)
# Link libraries including OpenSSL for SHA256 test # Link libraries
target_link_libraries(tests_run PRIVATE gtest gtest_main aaruformat) target_link_libraries(tests_run PRIVATE gtest gtest_main aaruformat)
# Link OpenSSL/LibreSSL for tests that use crypto functions directly
if(LIBRESSL_FOUND)
target_link_libraries(tests_run PRIVATE ${LIBRESSL_CRYPTO_LIBRARY})
elseif(OpenSSL_FOUND)
include_directories(${OPENSSL_INCLUDE_DIR})
target_link_libraries(tests_run PRIVATE ${OPENSSL_CRYPTO_LIBRARY})
endif()

View File

@@ -2,88 +2,117 @@
* This file is part of the Aaru Data Preservation Suite. * This file is part of the Aaru Data Preservation Suite.
* Copyright (c) 2019-2025 Natalia Portillo. * Copyright (c) 2019-2025 Natalia Portillo.
* *
* This library is free software; you can redistribute it and/or modify * Internal SHA-256 tests (no OpenSSL dependency).
* it under the terms of the GNU Lesser General Public License as * Validates implementation against standard FIPS 180-4 test vectors and the bundled random file.
* published by the Free Software Foundation; either version 2.1 of the
* License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/ */
#ifdef AARU_HAS_SHA256 #include <unistd.h>
#include <openssl/sha.h>
#include <climits> #include <climits>
#include <cstdint> #include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "decls.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "sha256.h"
static uint8_t *buffer; // Test vectors
static const unsigned char sha256_empty[SHA256_DIGEST_LENGTH] = {
0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24,
0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55};
unsigned char expected_sha256[SHA256_DIGEST_LENGTH] = {0x4d, 0x1a, 0x6b, 0x8a, 0x54, 0x67, 0x00, 0xc4, 0x8e, 0xda, 0x70, static const unsigned char sha256_abc[SHA256_DIGEST_LENGTH] = {
0xd3, 0x39, 0x1c, 0x8f, 0x15, 0x8a, 0x8d, 0x12, 0xb2, 0x38, 0x92, 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,
0x89, 0x29, 0x50, 0x47, 0x8c, 0x41, 0x8e, 0x25, 0xcc, 0x39}; 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad};
class sha256Fixture : public ::testing::Test // Previously validated expected SHA-256 of tests/data/random (1 MiB file)
static const unsigned char sha256_random[SHA256_DIGEST_LENGTH] = {
0x4d, 0x1a, 0x6b, 0x8a, 0x54, 0x67, 0x00, 0xc4, 0x8e, 0xda, 0x70, 0xd3, 0x39, 0x1c, 0x8f, 0x15,
0x8a, 0x8d, 0x12, 0xb2, 0x38, 0x92, 0x89, 0x29, 0x50, 0x47, 0x8c, 0x41, 0x8e, 0x25, 0xcc, 0x39};
#define EXPECT_ARRAY_EQ(expected, actual, len) \
for(size_t _i = 0; _i < (size_t)(len); ++_i) \
EXPECT_EQ(((const unsigned char *)(expected))[_i], ((const unsigned char *)(actual))[_i])
TEST(SHA256, EmptyOneShot)
{ {
public: unsigned char out[SHA256_DIGEST_LENGTH];
sha256Fixture() = default; aaruf_sha256_buffer("", 0, out);
EXPECT_ARRAY_EQ(sha256_empty, out, SHA256_DIGEST_LENGTH);
}
TEST(SHA256, ABCOneShot)
{
unsigned char out[SHA256_DIGEST_LENGTH];
const char *msg = "abc";
aaruf_sha256_buffer(msg, 3, out);
EXPECT_ARRAY_EQ(sha256_abc, out, SHA256_DIGEST_LENGTH);
}
TEST(SHA256, ABCStreaming)
{
unsigned char out[SHA256_DIGEST_LENGTH];
sha256_ctx ctx;
aaruf_sha256_init(&ctx);
const char *msg = "abc";
for(size_t i = 0; i < 3; i++) aaruf_sha256_update(&ctx, msg + i, 1);
aaruf_sha256_final(&ctx, out);
EXPECT_ARRAY_EQ(sha256_abc, out, SHA256_DIGEST_LENGTH);
}
class sha256RandomFixture : public ::testing::Test
{
protected: protected:
unsigned char *buffer = nullptr;
size_t size = 0;
void SetUp() override void SetUp() override
{ {
char path[PATH_MAX]; char path[PATH_MAX];
char filename[PATH_MAX]; char filename[PATH_MAX];
getcwd(path, PATH_MAX); getcwd(path, PATH_MAX);
snprintf(filename, PATH_MAX, "%s/data/random", path); snprintf(filename, PATH_MAX, "%s/data/random", path);
FILE *f = fopen(filename, "rb");
FILE *file = fopen(filename, "rb"); ASSERT_NE(f, nullptr) << "Failed to open random test file";
buffer = static_cast<uint8_t *>(malloc(1048576)); fseek(f, 0, SEEK_END);
fread(buffer, 1, 1048576, file); long sz = ftell(f);
fclose(file); ASSERT_GT(sz, 0);
fseek(f, 0, SEEK_SET);
buffer = (unsigned char *)malloc((size_t)sz);
ASSERT_NE(buffer, nullptr);
size = fread(buffer, 1, (size_t)sz, f);
fclose(f);
ASSERT_EQ(size, (size_t)sz);
} }
void TearDown() override { free(buffer); } void TearDown() override
{
~sha256Fixture() override = default; free(buffer);
buffer = nullptr;
// shared user data }
}; };
#define EXPECT_ARRAY_EQ(reference, actual, element_count) \ TEST_F(sha256RandomFixture, RandomFileOneShot)
{ \
unsigned char *reference_ = static_cast<unsigned char *>(reference); \
unsigned char *actual_ = static_cast<unsigned char *>(actual); \
for(int cmp_i = 0; cmp_i < (element_count); cmp_i++) { EXPECT_EQ(reference_[cmp_i], actual_[cmp_i]); } \
}
TEST_F(sha256Fixture, sha256)
{ {
unsigned char hash[SHA256_DIGEST_LENGTH]; unsigned char out[SHA256_DIGEST_LENGTH];
aaruf_sha256_buffer(buffer, (unsigned long)size, out);
SHA256_CTX *ctx = static_cast<SHA256_CTX *>(malloc(sizeof(SHA256_CTX))); EXPECT_ARRAY_EQ(sha256_random, out, SHA256_DIGEST_LENGTH);
EXPECT_NE(nullptr, ctx);
int ret = SHA256_Init(ctx);
EXPECT_EQ(ret, 1);
ret = SHA256_Update(ctx, buffer, 1048576);
EXPECT_EQ(ret, 1);
ret = SHA256_Final(hash, ctx);
EXPECT_EQ(ret, 1);
EXPECT_ARRAY_EQ(expected_sha256, hash, SHA256_DIGEST_LENGTH);
} }
#endif TEST_F(sha256RandomFixture, RandomFileStreaming_Chunk8K)
{
unsigned char out[SHA256_DIGEST_LENGTH];
sha256_ctx ctx;
aaruf_sha256_init(&ctx);
const size_t chunk = 8192;
size_t pos = 0;
while(pos < size)
{
size_t to_do = (size - pos) < chunk ? (size - pos) : chunk;
aaruf_sha256_update(&ctx, buffer + pos, (unsigned long)to_do);
pos += to_do;
}
aaruf_sha256_final(&ctx, out);
EXPECT_ARRAY_EQ(sha256_random, out, SHA256_DIGEST_LENGTH);
}