Sane C++ Libraries
C++ Platform Abstraction Libraries
Hashing.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "../Foundation/Span.h"
5namespace SC
6{
9
12
23struct Hashing
24{
25 struct Result
26 {
27 static constexpr auto MD5_DIGEST_LENGTH = 16;
28 static constexpr auto SHA1_DIGEST_LENGTH = 20;
29 static constexpr auto SHA256_DIGEST_LENGTH = 32;
30
31 uint8_t hash[32] = {0};
32 size_t size = 0;
33
34 Span<const uint8_t> toBytesSpan() const SC_LANGUAGE_LIFETIME_BOUND { return {hash, size}; }
35 };
36 enum Type
37 {
41 };
42
45
48
49 Hashing(const Hashing&) = delete;
50 Hashing(Hashing&&) = delete;
51 Hashing& operator=(const Hashing&) = delete;
52 Hashing& operator=(Hashing&&) = delete;
53
57 [[nodiscard]] bool add(Span<const uint8_t> data);
58
62 [[nodiscard]] bool getHash(Result& res);
63
67 [[nodiscard]] bool setType(Type newType);
68
69 private:
70#if SC_PLATFORM_APPLE
71 alignas(uint64_t) char buffer[104];
72#elif SC_PLATFORM_WINDOWS
73 alignas(uint64_t) char buffer[16];
74 struct CryptoPrivate;
75 bool destroyHash();
76#elif SC_PLATFORM_LINUX
77 int mainSocket = -1; // Not using FileDescriptor just to avoid dependency...
78 int hashSocket = -1;
79#endif
80 bool inited = false;
81 Type type = TypeMD5;
82};
84} // namespace SC
unsigned char uint8_t
Platform independent (1) byte unsigned int.
Definition: PrimitiveTypes.h:36
unsigned long long uint64_t
Platform independent (8) bytes unsigned int.
Definition: PrimitiveTypes.h:42
Definition: Hashing.h:26
Compute MD5, SHA1 or SHA256 hash for stream of data.
Definition: Hashing.h:24
Hashing()
Initializes an Hashing struct.
bool add(Span< const uint8_t > data)
Add data to be hashed.
~Hashing()
Destroys an Hashing struct.
bool setType(Type newType)
Set type of hash to compute.
Type
Definition: Hashing.h:37
@ TypeMD5
Compute MD5 hash for the incoming stream of bytes.
Definition: Hashing.h:38
@ TypeSHA1
Compute SHA1 hash for the incoming stream of bytes.
Definition: Hashing.h:39
@ TypeSHA256
Compute SHA256 hash for the incoming stream of bytes.
Definition: Hashing.h:40
bool getHash(Result &res)
Finalize hash computation that has been pushed through Hashing::add.
View over a contiguous sequence of items (pointer + size in elements).
Definition: Span.h:21