chore: import upstream snapshot with attribution
Awesome CI Workflow / Code Formatter (push) Has been cancelled
Awesome CI Workflow / Compile checks (macOS-latest) (push) Has been cancelled
Awesome CI Workflow / Compile checks (ubuntu-latest) (push) Has been cancelled
Awesome CI Workflow / Compile checks (windows-latest) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 12:37:28 +08:00
commit 29cfe479ab
432 changed files with 68491 additions and 0 deletions
+18
View File
@@ -0,0 +1,18 @@
# If necessary, use the RELATIVE flag, otherwise each source file may be listed
# with full pathname. RELATIVE may makes it easier to extract an executable name
# automatically.
file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp )
# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c )
# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES)
foreach( testsourcefile ${APP_SOURCES} )
# I used a simple string replace, to cut off .cpp.
string( REPLACE ".cpp" "" testname ${testsourcefile} )
add_executable( ${testname} ${testsourcefile} )
set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX)
if(OpenMP_CXX_FOUND)
target_link_libraries(${testname} OpenMP::OpenMP_CXX)
endif()
install(TARGETS ${testname} DESTINATION "bin/hash")
endforeach( testsourcefile ${APP_SOURCES} )
+186
View File
@@ -0,0 +1,186 @@
/**
* @file chaining.cpp
* @author [vasutomar](https://github.com/vasutomar)
* @author [Krishna Vedala](https://github.com/kvedala)
* @brief Implementation of [hash
* chains](https://en.wikipedia.org/wiki/Hash_chain).
*/
#include <cmath>
#include <iostream>
#include <memory>
#include <vector>
/**
* @brief Chain class with a given modulus
*/
class hash_chain {
private:
/**
* @brief Define a linked node
*/
using Node = struct Node {
int data{}; ///< data stored in the node
std::shared_ptr<struct Node> next; ///< pointer to the next node
};
std::vector<std::shared_ptr<Node>> head; ///< array of nodes
int _mod; ///< modulus of the class
public:
/**
* @brief Construct a new chain object
*
* @param mod modulus of the chain
*/
explicit hash_chain(int mod) : _mod(mod) {
while (mod--) head.push_back(nullptr);
}
/**
* @brief create and add a new node with a give value and at a given height
*
* @param x value at the new node
* @param h height of the node
*/
void add(int x, int h) {
std::shared_ptr<Node> curr;
std::shared_ptr<Node> temp(new Node);
temp->data = x;
temp->next = nullptr;
if (!head[h]) {
head[h] = temp;
curr = head[h];
} else {
curr = head[h];
while (curr->next) curr = curr->next;
curr->next = temp;
}
}
/**
* @brief Display the chain
*/
void display() {
std::shared_ptr<Node> temp = nullptr;
int i = 0;
for (i = 0; i < _mod; i++) {
if (!head[i]) {
std::cout << "Key " << i << " is empty" << std::endl;
} else {
std::cout << "Key " << i << " has values = " << std::endl;
temp = head[i];
while (temp->next) {
std::cout << temp->data << " " << std::endl;
temp = temp->next;
}
std::cout << temp->data;
std::cout << std::endl;
}
}
}
/**
* @brief Compute the hash of a value for current chain
*
* @param x value to compute modulus of
* @return modulus of `x`
* @note declared as a
* [`virtual`](https://en.cppreference.com/w/cpp/language/virtual) so that
* custom implementations of the class can modify the hash function.
*/
virtual int hash(int x) const { return x % _mod; }
/**
* @brief Find if a value and corresponding hash exist
*
* @param x value to search for
* @param h corresponding hash key
* @returns `true` if element found
* @returns `false` if element not found
*/
bool find(int x, int h) const {
std::shared_ptr<Node> temp = head[h];
if (!head[h]) {
// index does not exist!
std::cout << "Element not found" << std::endl;
return false;
}
// scan for data value
while (temp->data != x && temp->next) temp = temp->next;
if (temp->next) {
std::cout << "Element found" << std::endl;
return true;
}
// implicit else condition
// i.e., temp->next == nullptr
if (temp->data == x) {
std::cout << "Element found" << std::endl;
return true;
}
// further implicit else condition
std::cout << "Element not found" << std::endl;
return false;
}
};
/** Main function
* @returns `0` always
*/
int main() {
int c = 0, x = 0, mod = 0, h = 0;
std::cout << "Enter the size of Hash Table. = " << std::endl;
std::cin >> mod;
hash_chain mychain(mod);
bool loop = true;
while (loop) {
std::cout << std::endl;
std::cout << "PLEASE CHOOSE -" << std::endl;
std::cout << "1. Add element." << std::endl;
std::cout << "2. Find element." << std::endl;
std::cout << "3. Generate Hash." << std::endl;
std::cout << "4. Display Hash table." << std::endl;
std::cout << "5. Exit." << std::endl;
std::cin >> c;
switch (c) {
case 1:
std::cout << "Enter element to add = " << std::endl;
std::cin >> x;
h = mychain.hash(x);
h = std::abs(h);
mychain.add(x, h);
break;
case 2:
std::cout << "Enter element to search = " << std::endl;
std::cin >> x;
h = mychain.hash(x);
mychain.find(x, h);
break;
case 3:
std::cout << "Enter element to generate hash = " << std::endl;
std::cin >> x;
std::cout << "Hash of " << x << " is = " << mychain.hash(x)
<< std::endl;
break;
case 4:
mychain.display();
break;
default:
loop = false;
break;
}
std::cout << std::endl;
}
/*add(1,&head1);
add(2,&head1);
add(3,&head2);
add(5,&head1);
display(&head1);
display(&head2);*/
return 0;
}
+303
View File
@@ -0,0 +1,303 @@
/**
* @file double_hash_hash_table.cpp
* @author [achance6](https://github.com/achance6)
* @author [Krishna Vedala](https://github.com/kvedala)
* @brief Storage mechanism using [double-hashed
* keys](https://en.wikipedia.org/wiki/Double_hashing).
* @note The implementation can be optimized by using OOP style.
*/
#include <iostream>
#include <memory>
#include <vector>
/**
* @addtogroup open_addressing Open Addressing
* @{
* @namespace double_hashing
* @brief An implementation of hash table using [double
* hashing](https://en.wikipedia.org/wiki/Double_hashing) algorithm.
*/
namespace double_hashing {
// fwd declarations
using Entry = struct Entry;
bool putProber(const Entry& entry, int key);
bool searchingProber(const Entry& entry, int key);
void add(int key);
// Undocumented globals
int notPresent;
std::vector<Entry> table;
int totalSize;
int tomb = -1;
int size;
bool rehashing;
/** Node object that holds key */
struct Entry {
explicit Entry(int key = notPresent) : key(key) {} ///< constructor
int key; ///< key value
};
/**
* @brief Hash a key. Uses the STL library's `std::hash()` function.
*
* @param key value to hash
* @return hash value of the key
*/
size_t hashFxn(int key) {
std::hash<int> hash;
return hash(key);
}
/**
* @brief Used for second hash function
*
* @param key key value to hash
* @return hash value of the key
*/
size_t otherHashFxn(int key) {
std::hash<int> hash;
return 1 + (7 - (hash(key) % 7));
}
/**
* @brief Performs double hashing to resolve collisions
*
* @param key key value to apply double-hash on
* @param searching `true` to check for conflicts
* @return Index of key when found
* @return new hash if no conflicts present
*/
int doubleHash(int key, bool searching) {
int hash = static_cast<int>(hashFxn(key));
int i = 0;
Entry entry;
do {
int index =
static_cast<int>(hash + (i * otherHashFxn(key))) % totalSize;
entry = table[index];
if (searching) {
if (entry.key == notPresent) {
return notPresent;
}
if (searchingProber(entry, key)) {
std::cout << "Found key!" << std::endl;
return index;
}
std::cout << "Found tombstone or equal hash, checking next"
<< std::endl;
i++;
} else {
if (putProber(entry, key)) {
if (!rehashing) {
std::cout << "Spot found!" << std::endl;
}
return index;
}
if (!rehashing) {
std::cout << "Spot taken, looking at next (next index:"
<< " "
<< static_cast<int>(hash + (i * otherHashFxn(key))) %
totalSize
<< ")" << std::endl;
}
i++;
}
if (i == totalSize * 100) {
std::cout << "DoubleHash probe failed" << std::endl;
return notPresent;
}
} while (entry.key != notPresent);
return notPresent;
}
/** Finds empty spot in a vector
* @param entry vector to search in
* @param key key to search for
* @returns `true` if key is not present or is a `toumb`
* @returns `false` is already occupied
*/
bool putProber(const Entry& entry, int key) {
if (entry.key == notPresent || entry.key == tomb) {
return true;
}
return false;
}
/** Looks for a matching key
* @param entry vector to search in
* @param key key value to search
* @returns `true` if found
* @returns `false` if not found
*/
bool searchingProber(const Entry& entry, int key) {
if (entry.key == key) {
return true;
}
return false;
}
/** Displays the table
* @returns None
*/
void display() {
for (int i = 0; i < totalSize; i++) {
if (table[i].key == notPresent) {
std::cout << " Empty ";
} else if (table[i].key == tomb) {
std::cout << " Tomb ";
} else {
std::cout << " ";
std::cout << table[i].key;
std::cout << " ";
}
}
std::cout << std::endl;
}
/** Rehashes the table into a bigger table
* @returns None
*/
void rehash() {
// Necessary so wall of add info isn't printed all at once
rehashing = true;
int oldSize = totalSize;
std::vector<Entry> oldTable(table);
// Really this should use the next prime number greater than totalSize * 2
table = std::vector<Entry>(totalSize * 2);
totalSize *= 2;
for (int i = 0; i < oldSize; i++) {
if (oldTable[i].key != -1 && oldTable[i].key != notPresent) {
size--; // Size stays the same (add increments size)
add(oldTable[i].key);
}
}
// delete[] oldTable;
// oldTable.reset();
rehashing = false;
std::cout << "Table was rehashed, new size is: " << totalSize << std::endl;
}
/** Checks for load factor here
* @param key key value to add to the table
*/
void add(int key) {
// auto* entry = new Entry();
// entry->key = key;
int index = doubleHash(key, false);
table[index].key = key;
// Load factor greater than 0.5 causes resizing
if (++size / static_cast<double>(totalSize) >= 0.5) {
rehash();
}
}
/** Removes key. Leaves tombstone upon removal.
* @param key key value to remove
*/
void remove(int key) {
int index = doubleHash(key, true);
if (index == notPresent) {
std::cout << "key not found" << std::endl;
}
table[index].key = tomb;
std::cout << "Removal successful, leaving tombstone" << std::endl;
size--;
}
/** Information about the adding process
* @param key key value to add to table
*/
void addInfo(int key) {
std::cout << "Initial table: ";
display();
std::cout << std::endl;
std::cout << "hash of " << key << " is " << hashFxn(key) << " % "
<< totalSize << " == " << hashFxn(key) % totalSize;
std::cout << std::endl;
add(key);
std::cout << "New table: ";
display();
}
/** Information about removal process
* @param key key value to remove from table
*/
void removalInfo(int key) {
std::cout << "Initial table: ";
display();
std::cout << std::endl;
std::cout << "hash of " << key << " is " << hashFxn(key) << " % "
<< totalSize << " == " << hashFxn(key) % totalSize;
std::cout << std::endl;
remove(key);
std::cout << "New table: ";
display();
}
} // namespace double_hashing
/**
* @}
*/
using double_hashing::Entry;
using double_hashing::table;
using double_hashing::totalSize;
/** Main program
* @returns 0 on success
*/
int main() {
int cmd = 0, key = 0;
std::cout << "Enter the initial size of Hash Table. = ";
std::cin >> totalSize;
table = std::vector<Entry>(totalSize);
bool loop = true;
while (loop) {
std::cout << std::endl;
std::cout << "PLEASE CHOOSE -" << std::endl;
std::cout << "1. Add key. (Numeric only)" << std::endl;
std::cout << "2. Remove key." << std::endl;
std::cout << "3. Find key." << std::endl;
std::cout << "4. Generate Hash. (Numeric only)" << std::endl;
std::cout << "5. Display Hash table." << std::endl;
std::cout << "6. Exit." << std::endl;
std::cin >> cmd;
switch (cmd) {
case 1:
std::cout << "Enter key to add = ";
std::cin >> key;
double_hashing::addInfo(key);
break;
case 2:
std::cout << "Enter key to remove = ";
std::cin >> key;
double_hashing::removalInfo(key);
break;
case 3: {
std::cout << "Enter key to search = ";
std::cin >> key;
Entry entry = table[double_hashing::doubleHash(key, true)];
if (entry.key == double_hashing::notPresent) {
std::cout << "Key not present";
}
break;
}
case 4:
std::cout << "Enter element to generate hash = ";
std::cin >> key;
std::cout << "Hash of " << key
<< " is = " << double_hashing::hashFxn(key);
break;
case 5:
double_hashing::display();
break;
default:
loop = false;
break;
// delete[] table;
}
std::cout << std::endl;
}
return 0;
}
+277
View File
@@ -0,0 +1,277 @@
/**
* @file
* @author [achance6](https://github.com/achance6)
* @author [Krishna Vedala](https://github.com/kvedala)
* @brief Storage mechanism using [linear probing
* hash](https://en.wikipedia.org/wiki/Linear_probing) keys.
* @note The implementation can be optimized by using OOP style.
*/
#include <iostream>
#include <vector>
/**
* @addtogroup open_addressing Open Addressing
* @{
* @namespace linear_probing
* @brief An implementation of hash table using [linear
* probing](https://en.wikipedia.org/wiki/Linear_probing) algorithm.
*/
namespace linear_probing {
// fwd declarations
using Entry = struct Entry;
bool putProber(const Entry& entry, int key);
bool searchingProber(const Entry& entry, int key);
void add(int key);
// Undocumented globals
int notPresent;
std::vector<Entry> table;
int totalSize;
int tomb = -1;
int size;
bool rehashing;
/** Node object that holds key */
struct Entry {
explicit Entry(int key = notPresent) : key(key) {} ///< constructor
int key; ///< key value
};
/**
* @brief Hash a key. Uses the STL library's `std::hash()` function.
*
* @param key value to hash
* @return hash value of the key
*/
size_t hashFxn(int key) {
std::hash<int> hash;
return hash(key);
}
/** Performs linear probing to resolve collisions
* @param key key value to hash
* @return hash value of the key
*/
int linearProbe(int key, bool searching) {
int hash = static_cast<int>(hashFxn(key));
int i = 0;
Entry entry;
do {
int index = static_cast<int>((hash + i) % totalSize);
entry = table[index];
if (searching) {
if (entry.key == notPresent) {
return notPresent;
}
if (searchingProber(entry, key)) {
std::cout << "Found key!" << std::endl;
return index;
}
std::cout << "Found tombstone or equal hash, checking next"
<< std::endl;
i++;
} else {
if (putProber(entry, key)) {
if (!rehashing) {
std::cout << "Spot found!" << std::endl;
}
return index;
}
if (!rehashing) {
std::cout << "Spot taken, looking at next" << std::endl;
}
i++;
}
if (i == totalSize) {
std::cout << "Linear probe failed" << std::endl;
return notPresent;
}
} while (entry.key != notPresent);
return notPresent;
}
/** Finds empty spot
* @param entry instance to check in
* @param key key value to hash
* @return hash value of the key
*/
bool putProber(const Entry& entry, int key) {
if (entry.key == notPresent || entry.key == tomb) {
return true;
}
return false;
}
/** Looks for a matching key
* @param entry instance to check in
* @param key key value to hash
* @return hash value of the key
*/
bool searchingProber(const Entry& entry, int key) {
if (entry.key == key) {
return true;
}
return false;
}
/** Function to displays the table
* @returns none
*/
void display() {
for (int i = 0; i < totalSize; i++) {
if (table[i].key == notPresent) {
std::cout << " Empty ";
} else if (table[i].key == tomb) {
std::cout << " Tomb ";
} else {
std::cout << " ";
std::cout << table[i].key;
std::cout << " ";
}
}
std::cout << std::endl;
}
/** Rehashes the table into a bigger table
* @returns None
*/
void rehash() {
// Necessary so wall of add info isn't printed all at once
rehashing = true;
int oldSize = totalSize;
std::vector<Entry> oldTable(table);
// Really this should use the next prime number greater than totalSize *
// 2
totalSize *= 2;
table = std::vector<Entry>(totalSize);
for (int i = 0; i < oldSize; i++) {
if (oldTable[i].key != -1 && oldTable[i].key != notPresent) {
size--; // Size stays the same (add increments size)
add(oldTable[i].key);
}
}
// delete[] oldTable;
rehashing = false;
std::cout << "Table was rehashed, new size is: " << totalSize << std::endl;
}
/** Adds entry using linear probing. Checks for load factor here
* @param key key value to hash and add
*/
void add(int key) {
int index = linearProbe(key, false);
table[index].key = key;
// Load factor greater than 0.5 causes resizing
if (++size / static_cast<double>(totalSize) >= 0.5) {
rehash();
}
}
/** Removes key. Leaves tombstone upon removal.
* @param key key value to hash and remove
*/
void remove(int key) {
int index = linearProbe(key, true);
if (index == notPresent) {
std::cout << "key not found" << std::endl;
}
std::cout << "Removal Successful, leaving tomb" << std::endl;
table[index].key = tomb;
size--;
}
/** Information about the adding process
* @param key key value to hash and add
*/
void addInfo(int key) {
std::cout << "Initial table: ";
display();
std::cout << std::endl;
std::cout << "hash of " << key << " is " << hashFxn(key) << " % "
<< totalSize << " == " << hashFxn(key) % totalSize;
std::cout << std::endl;
add(key);
std::cout << "New table: ";
display();
}
/** Information about removal process
* @param key key value to hash and remove
*/
void removalInfo(int key) {
std::cout << "Initial table: ";
display();
std::cout << std::endl;
std::cout << "hash of " << key << " is " << hashFxn(key) << " % "
<< totalSize << " == " << hashFxn(key) % totalSize;
std::cout << std::endl;
remove(key);
std::cout << "New table: ";
display();
}
} // namespace linear_probing
/**
* @}
*/
using linear_probing::Entry;
using linear_probing::table;
using linear_probing::totalSize;
/** Main function
* @returns 0 on success
*/
int main() {
int cmd = 0, key = 0;
std::cout << "Enter the initial size of Hash Table. = ";
std::cin >> totalSize;
table = std::vector<Entry>(totalSize);
bool loop = true;
while (loop) {
std::cout << std::endl;
std::cout << "PLEASE CHOOSE -" << std::endl;
std::cout << "1. Add key. (Numeric only)" << std::endl;
std::cout << "2. Remove key." << std::endl;
std::cout << "3. Find key." << std::endl;
std::cout << "4. Generate Hash. (Numeric only)" << std::endl;
std::cout << "5. Display Hash table." << std::endl;
std::cout << "6. Exit." << std::endl;
std::cin >> cmd;
switch (cmd) {
case 1:
std::cout << "Enter key to add = ";
std::cin >> key;
linear_probing::addInfo(key);
break;
case 2:
std::cout << "Enter key to remove = ";
std::cin >> key;
linear_probing::removalInfo(key);
break;
case 3: {
std::cout << "Enter key to search = ";
std::cin >> key;
Entry entry = table[linear_probing::linearProbe(key, true)];
if (entry.key == linear_probing::notPresent) {
std::cout << "Key not present";
}
break;
}
case 4:
std::cout << "Enter element to generate hash = ";
std::cin >> key;
std::cout << "Hash of " << key
<< " is = " << linear_probing::hashFxn(key);
break;
case 5:
linear_probing::display();
break;
default:
loop = false;
break;
// delete[] table;
}
std::cout << std::endl;
}
return 0;
}
+384
View File
@@ -0,0 +1,384 @@
/**
* @file
* @author [tGautot](https://github.com/tGautot)
* @brief Simple C++ implementation of the [MD5 Hashing
* Algorithm](https://en.wikipedia.org/wiki/MD5)
* @details
* The [MD5 Algorithm](https://en.wikipedia.org/wiki/MD5) is a
* hashing algorithm which was designed in 1991 by [Ronal
* Rivest](https://en.wikipedia.org/wiki/Ron_Rivest).
*
* MD5 is one of the most used hashing algorithm there is. Some of its
* use cases are:
* 1. Providing checksum for downloaded software
* 2. Store salted password
*
* However MD5 has be know to be cryptographically weak for quite some
* time, yet it is still widely used. This weakness was exploited by the
* [Flame Malware](https://en.wikipedia.org/wiki/Flame_(malware)) in 2012
*
* ### Algorithm
* First of all, all values are expected to be in [little endian]
* (https://en.wikipedia.org/wiki/Endianness). This is especially important
* when using part of the bytestring as an integer.
*
* The first step of the algorithm is to pad the message for its length to
* be a multiple of 64 (bytes). This is done by first adding 0x80 (10000000)
* and then only zeroes until the last 8 bytes must be filled, where then the
* 64 bit size of the input will be added
*
* Once this is done, the algo breaks down this padded message
* into 64 bytes chunks. Each chunk is used for one *round*, a round
* breaks the chunk into 16 blocks of 4 bytes. During these rounds
* the algorithm will update its 128 bit state (represented by 4 ints: A,B,C,D)
* For more precisions on these operations please see the [Wikipedia
* aritcle](https://en.wikipedia.org/wiki/MD5#Algorithm).
* The signature given by MD5 is its 128 bit state once all rounds are done.
* @note This is a simple implementation for a byte string but
* some implmenetations can work on bytestream, messages of unknown length.
*/
#include <algorithm> /// Used for std::copy
#include <array> /// Used for std::array
#include <cassert> /// Used for assert
#include <cstdint>
#include <cstring> /// Used for std::memcopy
#include <iostream> /// Used for IO operations
#include <string> /// Used for strings
#include <vector> /// Used for std::vector
/**
* @namespace hashing
* @brief Hashing algorithms
*/
namespace hashing {
/**
* @namespace MD5
* @brief Functions for the [MD5](https://en.wikipedia.org/wiki/MD5) algorithm
* implementation
*/
namespace md5 {
/**
* @brief Rotates the bits of a 32-bit unsigned integer
* @param n Integer to rotate
* @param rotate How many bits for the rotation
* @return uint32_t The rotated integer
*/
uint32_t leftRotate32bits(uint32_t n, std::size_t rotate) {
return (n << rotate) | (n >> (32 - rotate));
}
/**
* @brief Checks whether integers are stored as big endian or not
* @note Taken from [this](https://stackoverflow.com/a/1001373) StackOverflow
* post
* @return true IF integers are detected to work as big-endian
* @return false IF integers are detected to work as little-endian
*/
bool isBigEndian() {
union {
uint32_t i;
std::array<char, 4> c;
} bint = {0x01020304};
return bint.c[0] == 1;
}
/**
* @brief Sets 32-bit integer to little-endian if needed
* @param n Number to set to little-endian (uint32_t)
* @return uint32_t param n with binary representation as little-endian
*/
uint32_t toLittleEndian32(uint32_t n) {
if (!isBigEndian()) {
return ((n << 24) & 0xFF000000) | ((n << 8) & 0x00FF0000) |
((n >> 8) & 0x0000FF00) | ((n >> 24) & 0x000000FF);
}
// Machine works on little endian, no need to change anything
return n;
}
/**
* @brief Sets 64-bit integer to little-endian if needed
* @param n Number to set to little-endian (uint64_t)
* @return uint64_t param n with binary representation as little-endian
*/
uint64_t toLittleEndian64(uint64_t n) {
if (!isBigEndian()) {
return ((n << 56) & 0xFF00000000000000) |
((n << 40) & 0x00FF000000000000) |
((n << 24) & 0x0000FF0000000000) |
((n << 8) & 0x000000FF00000000) |
((n >> 8) & 0x00000000FF000000) |
((n >> 24) & 0x0000000000FF0000) |
((n >> 40) & 0x000000000000FF00) |
((n >> 56) & 0x00000000000000FF);
;
}
// Machine works on little endian, no need to change anything
return n;
}
/**
* @brief Transforms the 128-bit MD5 signature into a 32 char hex string
* @param sig The MD5 signature (Expected 16 bytes)
* @return std::string The hex signature
*/
std::string sig2hex(void* sig) {
const char* hexChars = "0123456789abcdef";
auto* intsig = static_cast<uint8_t*>(sig);
std::string hex = "";
for (uint8_t i = 0; i < 16; i++) {
hex.push_back(hexChars[(intsig[i] >> 4) & 0xF]);
hex.push_back(hexChars[(intsig[i]) & 0xF]);
}
return hex;
}
/**
* @brief The MD5 algorithm itself, taking in a bytestring
* @param input_bs The bytestring to hash
* @param input_size The size (in BYTES) of the input
* @return void* Pointer to the 128-bit signature
*/
void* hash_bs(const void* input_bs, uint64_t input_size) {
auto* input = static_cast<const uint8_t*>(input_bs);
// Step 0: Initial Data (Those are decided in the MD5 protocol)
// s is the shift used in the leftrotate each round
std::array<uint32_t, 64> s = {
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21};
// K is pseudo-random values used each round
// The values can be obtained by the following python code:
/**
* @brief Values of K are pseudo-random and used to "salt" each round
* The values can be obtained by the following python code
* @code{.py}
* from math import floor, sin
*
* for i in range(64):
* print(floor(2**32 * abs(sin(i+1))))
* @endcode
*/
std::array<uint32_t, 64> K = {
3614090360, 3905402710, 606105819, 3250441966, 4118548399, 1200080426,
2821735955, 4249261313, 1770035416, 2336552879, 4294925233, 2304563134,
1804603682, 4254626195, 2792965006, 1236535329, 4129170786, 3225465664,
643717713, 3921069994, 3593408605, 38016083, 3634488961, 3889429448,
568446438, 3275163606, 4107603335, 1163531501, 2850285829, 4243563512,
1735328473, 2368359562, 4294588738, 2272392833, 1839030562, 4259657740,
2763975236, 1272893353, 4139469664, 3200236656, 681279174, 3936430074,
3572445317, 76029189, 3654602809, 3873151461, 530742520, 3299628645,
4096336452, 1126891415, 2878612391, 4237533241, 1700485571, 2399980690,
4293915773, 2240044497, 1873313359, 4264355552, 2734768916, 1309151649,
4149444226, 3174756917, 718787259, 3951481745};
// The initial 128-bit state
uint32_t a0 = 0x67452301, A = 0;
uint32_t b0 = 0xefcdab89, B = 0;
uint32_t c0 = 0x98badcfe, C = 0;
uint32_t d0 = 0x10325476, D = 0;
// Step 1: Processing the bytestring
// First compute the size the padded message will have
// so it is possible to allocate the right amount of memory
uint64_t padded_message_size = 0;
if (input_size % 64 < 56) {
padded_message_size = input_size + 64 - (input_size % 64);
} else {
padded_message_size = input_size + 128 - (input_size % 64);
}
std::vector<uint8_t> padded_message(padded_message_size);
// Beginning of the padded message is the original message
std::copy(input, input + input_size, padded_message.begin());
// Afterwards comes a single 1 bit and then only zeroes
padded_message[input_size] = 1 << 7; // 10000000
for (uint64_t i = input_size; i % 64 != 56; i++) {
if (i == input_size) {
continue; // pass first iteration
}
padded_message[i] = 0;
}
// We then have to add the 64-bit size of the message at the end
// When there is a conversion from int to bytestring or vice-versa
// We always need to make sure it is little endian
uint64_t input_bitsize_le = toLittleEndian64(input_size * 8);
for (uint8_t i = 0; i < 8; i++) {
padded_message[padded_message_size - 8 + i] =
(input_bitsize_le >> (56 - 8 * i)) & 0xFF;
}
// Already allocate memory for blocks
std::array<uint32_t, 16> blocks{};
// Rounds
for (uint64_t chunk = 0; chunk * 64 < padded_message_size; chunk++) {
// First, build the 16 32-bits blocks from the chunk
for (uint8_t bid = 0; bid < 16; bid++) {
blocks[bid] = 0;
// Having to build a 32-bit word from 4-bit words
// Add each and shift them to the left
for (uint8_t cid = 0; cid < 4; cid++) {
blocks[bid] = (blocks[bid] << 8) +
padded_message[chunk * 64 + bid * 4 + cid];
}
}
A = a0;
B = b0;
C = c0;
D = d0;
// Main "hashing" loop
for (uint8_t i = 0; i < 64; i++) {
uint32_t F = 0, g = 0;
if (i < 16) {
F = (B & C) | ((~B) & D);
g = i;
} else if (i < 32) {
F = (D & B) | ((~D) & C);
g = (5 * i + 1) % 16;
} else if (i < 48) {
F = B ^ C ^ D;
g = (3 * i + 5) % 16;
} else {
F = C ^ (B | (~D));
g = (7 * i) % 16;
}
// Update the accumulators
F += A + K[i] + toLittleEndian32(blocks[g]);
A = D;
D = C;
C = B;
B += leftRotate32bits(F, s[i]);
}
// Update the state with this chunk's hash
a0 += A;
b0 += B;
c0 += C;
d0 += D;
}
// Build signature from state
// Note, any type could be used for the signature
// uint8_t was used to make the 16 bytes obvious
// The sig needs to be little endian
auto* sig = new uint8_t[16];
for (uint8_t i = 0; i < 4; i++) {
sig[i] = (a0 >> (8 * i)) & 0xFF;
sig[i + 4] = (b0 >> (8 * i)) & 0xFF;
sig[i + 8] = (c0 >> (8 * i)) & 0xFF;
sig[i + 12] = (d0 >> (8 * i)) & 0xFF;
}
return sig;
}
/**
* @brief Converts the string to bytestring and calls the main algorithm
* @param message Plain character message to hash
* @return void* Pointer to the MD5 signature
*/
void* hash(const std::string& message) {
return hash_bs(&message[0], message.size());
}
} // namespace md5
} // namespace hashing
/**
* @brief Self-test implementations of well-known MD5 hashes
* @returns void
*/
static void test() {
// Hashes empty string and stores signature
void* sig = hashing::md5::hash("");
std::cout << "Hashing empty string" << std::endl;
// Prints signature hex representation
std::cout << hashing::md5::sig2hex(sig) << std::endl << std::endl;
// Test with cassert whether sig is correct from the expected value
assert(hashing::md5::sig2hex(sig).compare(
"d41d8cd98f00b204e9800998ecf8427e") == 0);
// Hashes "The quick brown fox jumps over the lazy dog" and stores signature
void* sig2 =
hashing::md5::hash("The quick brown fox jumps over the lazy dog");
std::cout << "Hashing The quick brown fox jumps over the lazy dog"
<< std::endl;
// Prints signature hex representation
std::cout << hashing::md5::sig2hex(sig2) << std::endl << std::endl;
// Test with cassert whether sig is correct from the expected value
assert(hashing::md5::sig2hex(sig2).compare(
"9e107d9d372bb6826bd81d3542a419d6") == 0);
// Hashes "The quick brown fox jumps over the lazy dog." (notice the
// additional period) and stores signature
void* sig3 =
hashing::md5::hash("The quick brown fox jumps over the lazy dog.");
std::cout << "Hashing "
"The quick brown fox jumps over the lazy dog."
<< std::endl;
// Prints signature hex representation
std::cout << hashing::md5::sig2hex(sig3) << std::endl << std::endl;
// Test with cassert whether sig is correct from the expected value
assert(hashing::md5::sig2hex(sig3).compare(
"e4d909c290d0fb1ca068ffaddf22cbd0") == 0);
// Hashes "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
// and stores signature
void* sig4 = hashing::md5::hash(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
std::cout
<< "Hashing "
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
<< std::endl;
// Prints signature hex representation
std::cout << hashing::md5::sig2hex(sig4) << std::endl << std::endl;
// Test with cassert whether sig is correct from the expected value
assert(hashing::md5::sig2hex(sig4).compare(
"d174ab98d277d9f5a5611c2c9f419d9f") == 0);
}
/**
* @brief Puts user in a loop where inputs can be given and MD5 hash will be
* computed and printed
* @returns void
*/
static void interactive() {
while (true) {
std::string input;
std::cout << "Enter a message to be hashed (Ctrl-C to exit): "
<< std::endl;
std::getline(std::cin, input);
void* sig = hashing::md5::hash(input);
std::cout << "Hash is: " << hashing::md5::sig2hex(sig) << std::endl;
while (true) {
std::cout << "Want to enter another message? (y/n) ";
std::getline(std::cin, input);
if (input.compare("y") == 0) {
break;
} else if (input.compare("n") == 0) {
return;
}
}
}
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
// Launch interactive mode where user can input messages and see
// their hash
interactive();
return 0;
}
+301
View File
@@ -0,0 +1,301 @@
/**
* @file
* @author [achance6](https://github.com/achance6)
* @author [Krishna Vedala](https://github.com/kvedala)
* @brief Storage mechanism using [quadratic probing
* hash](https://en.wikipedia.org/wiki/Quadratic_probing) keys.
* @note The implementation can be optimized by using OOP style.
*/
#include <cmath>
#include <iostream>
#include <vector>
/**
* @addtogroup open_addressing Open Addressing
* @{
* @namespace quadratic_probing
* @brief An implementation of hash table using [quadratic
* probing](https://en.wikipedia.org/wiki/Quadratic_probing) algorithm.
*/
namespace quadratic_probing {
// fwd declarations
using Entry = struct Entry;
bool putProber(const Entry& entry, int key);
bool searchingProber(const Entry& entry, int key);
void add(int key);
// globals
int notPresent;
std::vector<Entry> table;
int totalSize;
int tomb = -1;
int size;
bool rehashing;
/** Node that holds key
*/
struct Entry {
explicit Entry(int key = notPresent) : key(key) {} ///< constructor
int key; ///< key value
};
/** Hash a key
* @param key key value to hash
* @returns hash of the key
*/
size_t hashFxn(int key) {
std::hash<int> hash;
return hash(key);
}
/** Performs quadratic probing to resolve collisions
* @param key key value to search/probe
* @param searching `true` if only searching, `false1 if assigning
* @returns value of `notPresent`.
*/
int quadraticProbe(int key, bool searching) {
int hash = static_cast<int>(hashFxn(key));
int i = 0;
Entry entry;
do {
size_t index =
(hash + static_cast<size_t>(std::round(std::pow(i, 2)))) %
totalSize;
entry = table[index];
if (searching) {
if (entry.key == notPresent) {
return notPresent;
}
if (searchingProber(entry, key)) {
std::cout << "Found key!" << std::endl;
return index;
}
std::cout << "Found tombstone or equal hash, checking next"
<< std::endl;
i++;
} else {
if (putProber(entry, key)) {
if (!rehashing) {
std::cout << "Spot found!" << std::endl;
}
return index;
}
if (!rehashing) {
std::cout << "Spot taken, looking at next (next index = "
<< (hash + static_cast<size_t>(
std::round(std::pow(i + 1, 2)))) %
totalSize
<< std::endl;
}
i++;
}
if (i == totalSize * 100) {
std::cout << "Quadratic probe failed (infinite loop)" << std::endl;
return notPresent;
}
} while (entry.key != notPresent);
return notPresent;
}
/** Finds empty spot
* @param entry Instance of table entry
* @param key key value to search/probe
* @returns `true` if key is present
* @returns `false` if key is absent
*/
bool putProber(const Entry& entry, int key) {
if (entry.key == notPresent || entry.key == tomb) {
return true;
}
return false;
}
/** Looks for a matching key
* @param entry Instance of table entry
* @param key key value to search/probe
* @returns `true` if key matches the entry
* @returns `false` if key does not match the entry
*/
bool searchingProber(const Entry& entry, int key) {
if (entry.key == key) {
return true;
}
return false;
}
/** Get the entry instance corresponding to a key
* @param key key value to search/probe
* @returns if present, the entry instance
* @returns if not present, a new instance
*/
Entry find(int key) {
int index = quadraticProbe(key, true);
if (index == notPresent) {
return Entry();
}
return table[index];
}
/** Displays the table
* @returns None
*/
void display() {
for (int i = 0; i < totalSize; i++) {
if (table[i].key == notPresent) {
std::cout << " Empty ";
} else if (table[i].key == tomb) {
std::cout << " Tomb ";
} else {
std::cout << " ";
std::cout << table[i].key;
std::cout << " ";
}
}
std::cout << std::endl;
}
/** Rehashes the table into a bigger table
* @returns none
*/
void rehash() {
// Necessary so wall of add info isn't printed all at once
rehashing = true;
int oldSize = totalSize;
std::vector<Entry> oldTable(table);
// Really this should use the next prime number greater than totalSize * 2
totalSize *= 2;
table = std::vector<Entry>(totalSize);
for (int i = 0; i < oldSize; i++) {
if (oldTable[i].key != -1 && oldTable[i].key != notPresent) {
size--; // Size stays the same (add increments size)
add(oldTable[i].key);
}
}
// delete[] oldTable;
rehashing = false;
std::cout << "Table was rehashed, new size is: " << totalSize << std::endl;
}
/** Checks for load factor here
* @param key key value to hash and add to table
*/
void add(int key) {
int index = quadraticProbe(key, false);
table[index].key = key;
// Load factor greater than 0.5 causes resizing
if (++size / static_cast<double>(totalSize) >= 0.5) {
rehash();
}
}
/** Removes key. Leaves tombstone upon removal.
* @param key key value to hash and remove from table
*/
void remove(int key) {
int index = quadraticProbe(key, true);
if (index == notPresent) {
std::cout << "key not found" << std::endl;
}
table[index].key = tomb;
std::cout << "Removal successful, leaving tombstone" << std::endl;
size--;
}
/** Information about the adding process
* @param key key value to hash and add to table
*/
void addInfo(int key) {
std::cout << "Initial table: ";
display();
std::cout << std::endl;
std::cout << "hash of " << key << " is " << hashFxn(key) << " % "
<< totalSize << " == " << hashFxn(key) % totalSize;
std::cout << std::endl;
add(key);
std::cout << "New table: ";
display();
}
/** Information about removal process
* @param key key value to hash and remove from table
*/
void removalInfo(int key) {
std::cout << "Initial table: ";
display();
std::cout << std::endl;
std::cout << "hash of " << key << " is " << hashFxn(key) << " % "
<< totalSize << " == " << hashFxn(key) % totalSize;
std::cout << std::endl;
remove(key);
std::cout << "New table: ";
display();
}
} // namespace quadratic_probing
/**
* @}
*/
using quadratic_probing::Entry;
using quadratic_probing::table;
using quadratic_probing::totalSize;
/** Main function
* @returns None
*/
int main() {
int cmd = 0, key = 0;
std::cout << "Enter the initial size of Hash Table. = ";
std::cin >> totalSize;
table = std::vector<Entry>(totalSize);
bool loop = true;
while (loop) {
std::cout << std::endl;
std::cout << "PLEASE CHOOSE -" << std::endl;
std::cout << "1. Add key. (Numeric only)" << std::endl;
std::cout << "2. Remove key." << std::endl;
std::cout << "3. Find key." << std::endl;
std::cout << "4. Generate Hash. (Numeric only)" << std::endl;
std::cout << "5. Display Hash table." << std::endl;
std::cout << "6. Exit." << std::endl;
std::cin >> cmd;
switch (cmd) {
case 1:
std::cout << "Enter key to add = ";
std::cin >> key;
quadratic_probing::addInfo(key);
break;
case 2:
std::cout << "Enter key to remove = ";
std::cin >> key;
quadratic_probing::removalInfo(key);
break;
case 3: {
std::cout << "Enter key to search = ";
std::cin >> key;
quadratic_probing::Entry entry =
quadratic_probing::table[quadratic_probing::quadraticProbe(
key, true)];
if (entry.key == quadratic_probing::notPresent) {
std::cout << "Key not present";
}
break;
}
case 4:
std::cout << "Enter element to generate hash = ";
std::cin >> key;
std::cout << "Hash of " << key
<< " is = " << quadratic_probing::hashFxn(key);
break;
case 5:
quadratic_probing::display();
break;
default:
loop = false;
break;
// delete[] table;
}
std::cout << std::endl;
}
return 0;
}
+307
View File
@@ -0,0 +1,307 @@
/**
* @file
* @author [tGautot](https://github.com/tGautot)
* @brief Simple C++ implementation of the [SHA-1 Hashing
* Algorithm](https://en.wikipedia.org/wiki/SHA-1)
*
* @details
* [SHA-1](https://en.wikipedia.org/wiki/SHA-1) is a cryptographic hash function
* that was developped by the
* [NSA](https://en.wikipedia.org/wiki/National_Security_Agency) 1995.
* SHA-1 is not considered secure since around 2010.
*
* ### Algorithm
* The first step of the algorithm is to pad the message for its length to
* be a multiple of 64 (bytes). This is done by first adding 0x80 (10000000)
* and then only zeroes until the last 8 bytes must be filled, where then the
* 64 bit size of the input will be added
*
* Once this is done, the algo breaks down this padded message
* into 64 bytes chunks. Each chunk is used for one *round*, a round
* breaks the chunk into 16 blocks of 4 bytes. These 16 blocks are then extended
* to 80 blocks using XOR operations on existing blocks (see code for more
* details). The algorithm will then update its 160-bit state (here represented
* used 5 32-bits integer) using partial hashes computed using special functions
* on the blocks previously built. Please take a look at the [wikipedia
* article](https://en.wikipedia.org/wiki/SHA-1#SHA-1_pseudocode) for more
* precision on these operations
* @note This is a simple implementation for a byte string but
* some implmenetations can work on bytestream, messages of unknown length.
*/
#include <algorithm> /// For std::copy
#include <array> /// For std::array
#include <cassert> /// For assert
#include <cstdint>
#include <cstring> /// For std::memcopy
#include <iostream> /// For IO operations
#include <string> /// For strings
#include <vector> /// For std::vector
/**
* @namespace hashing
* @brief Hashing algorithms
*/
namespace hashing {
/**
* @namespace SHA-1
* @brief Functions for the [SHA-1](https://en.wikipedia.org/wiki/SHA-1)
* algorithm implementation
*/
namespace sha1 {
/**
* @brief Rotates the bits of a 32-bit unsigned integer
* @param n Integer to rotate
* @param rotate How many bits for the rotation
* @return uint32_t The rotated integer
*/
uint32_t leftRotate32bits(uint32_t n, std::size_t rotate) {
return (n << rotate) | (n >> (32 - rotate));
}
/**
* @brief Transforms the 160-bit SHA-1 signature into a 40 char hex string
* @param sig The SHA-1 signature (Expected 20 bytes)
* @return std::string The hex signature
*/
std::string sig2hex(void* sig) {
const char* hexChars = "0123456789abcdef";
auto* intsig = static_cast<uint8_t*>(sig);
std::string hex = "";
for (uint8_t i = 0; i < 20; i++) {
hex.push_back(hexChars[(intsig[i] >> 4) & 0xF]);
hex.push_back(hexChars[(intsig[i]) & 0xF]);
}
return hex;
}
/**
* @brief The SHA-1 algorithm itself, taking in a bytestring
* @param input_bs The bytestring to hash
* @param input_size The size (in BYTES) of the input
* @return void* Pointer to the 160-bit signature
*/
void* hash_bs(const void* input_bs, uint64_t input_size) {
auto* input = static_cast<const uint8_t*>(input_bs);
// Step 0: The initial 160-bit state
uint32_t h0 = 0x67452301, a = 0;
uint32_t h1 = 0xEFCDAB89, b = 0;
uint32_t h2 = 0x98BADCFE, c = 0;
uint32_t h3 = 0x10325476, d = 0;
uint32_t h4 = 0xC3D2E1F0, e = 0;
// Step 1: Processing the bytestring
// First compute the size the padded message will have
// so it is possible to allocate the right amount of memory
uint64_t padded_message_size = 0;
if (input_size % 64 < 56) {
padded_message_size = input_size + 64 - (input_size % 64);
} else {
padded_message_size = input_size + 128 - (input_size % 64);
}
// Allocate the memory for the padded message
std::vector<uint8_t> padded_message(padded_message_size);
// Beginning of the padded message is the original message
std::copy(input, input + input_size, padded_message.begin());
// Afterwards comes a single 1 bit and then only zeroes
padded_message[input_size] = 1 << 7; // 10000000
for (uint64_t i = input_size; i % 64 != 56; i++) {
if (i == input_size) {
continue; // pass first iteration
}
padded_message[i] = 0;
}
// We then have to add the 64-bit size of the message in bits (hence the
// times 8) in the last 8 bytes
uint64_t input_bitsize = input_size * 8;
for (uint8_t i = 0; i < 8; i++) {
padded_message[padded_message_size - 8 + i] =
(input_bitsize >> (56 - 8 * i)) & 0xFF;
}
// Already allocate memory for blocks
std::array<uint32_t, 80> blocks{};
// Rounds
for (uint64_t chunk = 0; chunk * 64 < padded_message_size; chunk++) {
// First, build 16 32-bits blocks from the chunk
for (uint8_t bid = 0; bid < 16; bid++) {
blocks[bid] = 0;
// Having to build a 32-bit word from 4-bit words
// Add each and shift them to the left
for (uint8_t cid = 0; cid < 4; cid++) {
blocks[bid] = (blocks[bid] << 8) +
padded_message[chunk * 64 + bid * 4 + cid];
}
// Extend the 16 32-bit words into 80 32-bit words
for (uint8_t i = 16; i < 80; i++) {
blocks[i] =
leftRotate32bits(blocks[i - 3] ^ blocks[i - 8] ^
blocks[i - 14] ^ blocks[i - 16],
1);
}
}
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
// Main "hashing" loop
for (uint8_t i = 0; i < 80; i++) {
uint32_t F = 0, g = 0;
if (i < 20) {
F = (b & c) | ((~b) & d);
g = 0x5A827999;
} else if (i < 40) {
F = b ^ c ^ d;
g = 0x6ED9EBA1;
} else if (i < 60) {
F = (b & c) | (b & d) | (c & d);
g = 0x8F1BBCDC;
} else {
F = b ^ c ^ d;
g = 0xCA62C1D6;
}
// Update the accumulators
uint32_t temp = leftRotate32bits(a, 5) + F + e + g + blocks[i];
e = d;
d = c;
c = leftRotate32bits(b, 30);
b = a;
a = temp;
}
// Update the state with this chunk's hash
h0 += a;
h1 += b;
h2 += c;
h3 += d;
h4 += e;
}
// Build signature from state
// Note, any type could be used for the signature
// uint8_t was used to make the 20 bytes obvious
auto* sig = new uint8_t[20];
for (uint8_t i = 0; i < 4; i++) {
sig[i] = (h0 >> (24 - 8 * i)) & 0xFF;
sig[i + 4] = (h1 >> (24 - 8 * i)) & 0xFF;
sig[i + 8] = (h2 >> (24 - 8 * i)) & 0xFF;
sig[i + 12] = (h3 >> (24 - 8 * i)) & 0xFF;
sig[i + 16] = (h4 >> (24 - 8 * i)) & 0xFF;
}
return sig;
}
/**
* @brief Converts the string to bytestring and calls the main algorithm
* @param message Plain character message to hash
* @return void* Pointer to the SHA-1 signature
*/
void* hash(const std::string& message) {
return hash_bs(&message[0], message.size());
}
} // namespace sha1
} // namespace hashing
/**
* @brief Self-test implementations of well-known SHA-1 hashes
* @returns void
*/
static void test() {
// Hashes empty string and stores signature
void* sig = hashing::sha1::hash("");
std::cout << "Hashing empty string" << std::endl;
// Prints signature hex representation
std::cout << hashing::sha1::sig2hex(sig) << std::endl << std::endl;
// Test with cassert wether sig is correct from expected value
assert(hashing::sha1::sig2hex(sig).compare(
"da39a3ee5e6b4b0d3255bfef95601890afd80709") == 0);
// Hashes "The quick brown fox jumps over the lazy dog" and stores signature
void* sig2 =
hashing::sha1::hash("The quick brown fox jumps over the lazy dog");
std::cout << "Hashing The quick brown fox jumps over the lazy dog"
<< std::endl;
// Prints signature hex representation
std::cout << hashing::sha1::sig2hex(sig2) << std::endl << std::endl;
// Test with cassert wether sig is correct from expected value
assert(hashing::sha1::sig2hex(sig2).compare(
"2fd4e1c67a2d28fced849ee1bb76e7391b93eb12") == 0);
// Hashes "The quick brown fox jumps over the lazy dog." (notice the
// additional period) and stores signature
void* sig3 =
hashing::sha1::hash("The quick brown fox jumps over the lazy dog.");
std::cout << "Hashing "
"The quick brown fox jumps over the lazy dog."
<< std::endl;
// Prints signature hex representation
std::cout << hashing::sha1::sig2hex(sig3) << std::endl << std::endl;
// Test with cassert wether sig is correct from expected value
assert(hashing::sha1::sig2hex(sig3).compare(
"408d94384216f890ff7a0c3528e8bed1e0b01621") == 0);
// Hashes "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
// and stores signature
void* sig4 = hashing::sha1::hash(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
std::cout
<< "Hashing "
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
<< std::endl;
// Prints signature hex representation
std::cout << hashing::sha1::sig2hex(sig4) << std::endl << std::endl;
// Test with cassert wether sig is correct from expected value
assert(hashing::sha1::sig2hex(sig4).compare(
"761c457bf73b14d27e9e9265c46f4b4dda11f940") == 0);
}
/**
* @brief Puts user in a loop where inputs can be given and SHA-1 hash will be
* computed and printed
* @returns void
*/
static void interactive() {
while (true) {
std::string input;
std::cout << "Enter a message to be hashed (Ctrl-C to exit): "
<< std::endl;
std::getline(std::cin, input);
void* sig = hashing::sha1::hash(input);
std::cout << "Hash is: " << hashing::sha1::sig2hex(sig) << std::endl;
while (true) {
std::cout << "Want to enter another message? (y/n) ";
std::getline(std::cin, input);
if (input.compare("y") == 0) {
break;
} else if (input.compare("n") == 0) {
return;
}
}
}
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
// Launch interactive mode where user can input messages and see
// their hash
interactive();
return 0;
}
+329
View File
@@ -0,0 +1,329 @@
/**
* @file
* @author [Md. Anisul Haque](https://github.com/mdanisulh)
* @brief Simple C++ implementation of the [SHA-256 Hashing Algorithm]
* (https://en.wikipedia.org/wiki/SHA-2)
*
* @details
* [SHA-2](https://en.wikipedia.org/wiki/SHA-2) is a set of cryptographic hash
* functions that was designed by the
* [NSA](https://en.wikipedia.org/wiki/National_Security_Agency) and first
* published in 2001. SHA-256 is a part of the SHA-2 family. SHA-256 is widely
* used for authenticating software packages and secure password hashing.
*/
#include <array> /// For std::array
#include <cassert> /// For assert
#include <cstdint> /// For uint8_t, uint32_t and uint64_t data types
#include <iomanip> /// For std::setfill and std::setw
#include <iostream> /// For IO operations
#include <sstream> /// For std::stringstream
#include <utility> /// For std::move
#include <vector> /// For std::vector
/**
* @namespace hashing
* @brief Hashing algorithms
*/
namespace hashing {
/**
* @namespace SHA-256
* @brief Functions for the [SHA-256](https://en.wikipedia.org/wiki/SHA-2)
* algorithm implementation
*/
namespace sha256 {
/**
* @class Hash
* @brief Contains hash array and functions to update it and convert it to a
* hexadecimal string
*/
class Hash {
// Initialize array of hash values with first 32 bits of the fractional
// parts of the square roots of the first 8 primes 2..19
std::array<uint32_t, 8> hash = {0x6A09E667, 0xBB67AE85, 0x3C6EF372,
0xA54FF53A, 0x510E527F, 0x9B05688C,
0x1F83D9AB, 0x5BE0CD19};
public:
void update(const std::array<uint32_t, 64> &blocks);
std::string to_string() const;
};
/**
* @brief Rotates the bits of a 32-bit unsigned integer
* @param n Integer to rotate
* @param rotate Number of bits to rotate
* @return uint32_t The rotated integer
*/
uint32_t right_rotate(uint32_t n, size_t rotate) {
return (n >> rotate) | (n << (32 - rotate));
}
/**
* @brief Updates the hash array
* @param blocks Message schedule array
* @return void
*/
void Hash::update(const std::array<uint32_t, 64> &blocks) {
// Initialize array of round constants with first 32 bits of the fractional
// parts of the cube roots of the first 64 primes 2..311
const std::array<uint32_t, 64> round_constants = {
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};
// Initialize working variables
auto a = hash[0];
auto b = hash[1];
auto c = hash[2];
auto d = hash[3];
auto e = hash[4];
auto f = hash[5];
auto g = hash[6];
auto h = hash[7];
// Compression function main loop
for (size_t block_num = 0; block_num < 64; ++block_num) {
const auto s1 =
right_rotate(e, 6) ^ right_rotate(e, 11) ^ right_rotate(e, 25);
const auto ch = (e & f) ^ (~e & g);
const auto temp1 =
h + s1 + ch + round_constants[block_num] + blocks[block_num];
const auto s0 =
right_rotate(a, 2) ^ right_rotate(a, 13) ^ right_rotate(a, 22);
const auto maj = (a & b) ^ (a & c) ^ (b & c);
const auto temp2 = s0 + maj;
h = g;
g = f;
f = e;
e = d + temp1;
d = c;
c = b;
b = a;
a = temp1 + temp2;
}
// Update hash values
hash[0] += a;
hash[1] += b;
hash[2] += c;
hash[3] += d;
hash[4] += e;
hash[5] += f;
hash[6] += g;
hash[7] += h;
}
/**
* @brief Convert the hash to a hexadecimal string
* @return std::string Final hash value
*/
std::string Hash::to_string() const {
std::stringstream ss;
for (size_t i = 0; i < 8; ++i) {
ss << std::hex << std::setfill('0') << std::setw(8) << hash[i];
}
return ss.str();
}
/**
* @brief Computes size of the padded input
* @param input Input string
* @return size_t Size of the padded input
*/
std::size_t compute_padded_size(const std::size_t input_size) {
if (input_size % 64 < 56) {
return input_size + 64 - (input_size % 64);
}
return input_size + 128 - (input_size % 64);
}
/**
* @brief Returns the byte at position byte_num in in_value
* @param in_value Input value
* @param byte_num Position of byte to be returned
* @return uint8_t Byte at position byte_num
*/
template <typename T>
uint8_t extract_byte(const T in_value, const std::size_t byte_num) {
if (sizeof(in_value) <= byte_num) {
throw std::out_of_range("Byte at index byte_num does not exist");
}
return (in_value >> (byte_num * 8)) & 0xFF;
}
/**
* @brief Returns the character at pos after the input is padded
* @param input Input string
* @param pos Position of character to be returned
* @return char Character at the index pos in the padded string
*/
char get_char(const std::string &input, std::size_t pos) {
const auto input_size = input.length();
if (pos < input_size) {
return input[pos];
}
if (pos == input_size) {
return '\x80';
}
const auto padded_input_size = compute_padded_size(input_size);
if (pos < padded_input_size - 8) {
return '\x00';
}
if (padded_input_size <= pos) {
throw std::out_of_range("pos is out of range");
}
return static_cast<char>(
extract_byte<size_t>(input_size * 8, padded_input_size - pos - 1));
}
/**
* @brief Creates the message schedule array
* @param input Input string
* @param byte_num Position of the first byte of the chunk
* @return std::array<uint32_t, 64> Message schedule array
*/
std::array<uint32_t, 64> create_message_schedule_array(const std::string &input,
const size_t byte_num) {
std::array<uint32_t, 64> blocks{};
// Copy chunk into first 16 words of the message schedule array
for (size_t block_num = 0; block_num < 16; ++block_num) {
blocks[block_num] =
(static_cast<uint8_t>(get_char(input, byte_num + block_num * 4))
<< 24) |
(static_cast<uint8_t>(get_char(input, byte_num + block_num * 4 + 1))
<< 16) |
(static_cast<uint8_t>(get_char(input, byte_num + block_num * 4 + 2))
<< 8) |
static_cast<uint8_t>(get_char(input, byte_num + block_num * 4 + 3));
}
// Extend the first 16 words into remaining 48 words of the message schedule
// array
for (size_t block_num = 16; block_num < 64; ++block_num) {
const auto s0 = right_rotate(blocks[block_num - 15], 7) ^
right_rotate(blocks[block_num - 15], 18) ^
(blocks[block_num - 15] >> 3);
const auto s1 = right_rotate(blocks[block_num - 2], 17) ^
right_rotate(blocks[block_num - 2], 19) ^
(blocks[block_num - 2] >> 10);
blocks[block_num] =
blocks[block_num - 16] + s0 + blocks[block_num - 7] + s1;
}
return blocks;
}
/**
* @brief Computes the final hash value
* @param input Input string
* @return std::string The final hash value
*/
std::string sha256(const std::string &input) {
Hash h;
// Process message in successive 512-bit (64-byte) chunks
for (size_t byte_num = 0; byte_num < compute_padded_size(input.length());
byte_num += 64) {
h.update(create_message_schedule_array(input, byte_num));
}
return h.to_string();
}
} // namespace sha256
} // namespace hashing
/**
* @brief Self-test implementations
* @returns void
*/
static void test_compute_padded_size() {
assert(hashing::sha256::compute_padded_size(55) == 64);
assert(hashing::sha256::compute_padded_size(56) == 128);
assert(hashing::sha256::compute_padded_size(130) == 192);
}
static void test_extract_byte() {
assert(hashing::sha256::extract_byte<uint32_t>(512, 0) == 0);
assert(hashing::sha256::extract_byte<uint32_t>(512, 1) == 2);
bool exception = false;
try {
hashing::sha256::extract_byte<uint32_t>(512, 5);
} catch (const std::out_of_range &) {
exception = true;
}
assert(exception);
}
static void test_get_char() {
assert(hashing::sha256::get_char("test", 3) == 't');
assert(hashing::sha256::get_char("test", 4) == '\x80');
assert(hashing::sha256::get_char("test", 5) == '\x00');
assert(hashing::sha256::get_char("test", 63) == 32);
bool exception = false;
try {
hashing::sha256::get_char("test", 64);
} catch (const std::out_of_range &) {
exception = true;
}
assert(exception);
}
static void test_right_rotate() {
assert(hashing::sha256::right_rotate(128, 3) == 16);
assert(hashing::sha256::right_rotate(1, 30) == 4);
assert(hashing::sha256::right_rotate(6, 30) == 24);
}
static void test_sha256() {
struct TestCase {
const std::string input;
const std::string expected_hash;
TestCase(std::string input, std::string expected_hash)
: input(std::move(input)),
expected_hash(std::move(expected_hash)) {}
};
const std::vector<TestCase> test_cases{
TestCase(
"",
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"),
TestCase(
"test",
"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"),
TestCase(
"Hello World",
"a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e"),
TestCase("Hello World!",
"7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9"
"069")};
for (const auto &tc : test_cases) {
assert(hashing::sha256::sha256(tc.input) == tc.expected_hash);
}
}
static void test() {
test_compute_padded_size();
test_extract_byte();
test_get_char();
test_right_rotate();
test_sha256();
std::cout << "All tests have successfully passed!\n";
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // Run self-test implementations
return 0;
}