View Single Post
Author Message
SirDigby
Junior Member
Join Date: Feb 2016
Old 07-29-2022 , 00:48   [INC] SHA-256 Hash Function
Reply With Quote #1

[INC] SHA-256 Hash Function

A single file include with a SHA-256 hash function.
Supports UTF-8 text, hexadecimal or binary string inputs.

Disclaimer
While I have tested this code and it seems to work pretty well, I can't guarantee it's 100% working and bug free.
If you're using this for any security purposes, you use it at your own risk.
And also, you shouldn't be using SHA-256 for securing anything anyway.

Example Code
PHP Code:
/**
 * Generate a SHA-256 hash of a string of input data.
 * Input data can be in UTF-8, hexadecimal or binary.
 *
 * @param input     Input data (UTF-8 text, hexadecimal bytes or binary bytes).
 * @param output    Output buffer.
 * @param size      Size of output buffer.
 * @param mode      How to interpret input data.
 */
stock void SHA256(const char[] inputchar[] outputint sizeStrInputMode mode String_UTF8
PHP Code:
char output[HASH_SIZE_256BIT]; // size 65

/* Text (UTF-8) */
SHA256("The quick brown fox jumps over the lazy dog"outputsizeof(output));
// output = "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
SHA256("The quick brown fox jumps over the lazy dog?"outputsizeof(output));
// output = "f77bc0c0d0779a6b329c7b9e847acb3797734ae531f08cc9d44cb4124d6e2b16"


/* Hexadecimal bytes (Case-insensitive) */
SHA256("AA0066FFDEADBEEF"outputsizeof(output), String_Hex);
// output = "1a61db0b7dc6ba6812d73eb6acdd2e84271c1124b0ec684192aca6f0933045a8"


/* Binary bytes */
SHA256("011000010110001001100011"outputsizeof(output), String_Binary);
// or SHA256("abc", output, sizeof(output), String_UTF8);
// output = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" 
How do I know it works?
The code has been tested with the NIST's publically available tests SHA Test Vectors for Hashing Byte-Oriented Messages
provided by their Cryptographic Algorithm Validation Program.
The tests are provided in the repo along with the python script to generate the test plugin from the original .rsp files.

No, that doesn't mean this code is officially validated.

The only one test that consistently fails is the "00" (0x00) test, which is because the test is wrong.
That test assumes a null string (length 0) is the same as a null byte (0x00, length 1).
Other SHA-256 implementations will fail this test too (like 7-Zip's).


Download sha256.inc


If you find any bugs or issues let me know.
Attached Files
File Type: inc sha256.inc (15.5 KB, 105 views)
__________________

Last edited by SirDigby; 08-02-2022 at 05:00.
SirDigby is offline