Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute hash for structure

Tags:

c++

hash

sha256

sha

I am looking for solution how to compute hash for data structure. Let's assume we have a structure like this:

struct A
{
    float64_t array[4][4];
    float64_t x;
    float64_t y;
    uint8_t validationHash[32]; // here computed hash need to be stored
}

I also have function Sha256(cont char * input, uint8_t (&output)[32]) which as an arguments takes input and output - computed hash. I know that i need to convert each value from structure to const char *. But my question is what to do next, shall I compute a separate hash for each value from array, x and y and add them together or what?

Implementation of Sha256 is the same like here http://www.zedwood.com/article/cpp-sha256-function

like image 649
Mateusz Czerepowicki Avatar asked Jan 18 '26 11:01

Mateusz Czerepowicki


1 Answers

The SHA-256 hash function you linked to, like most cryptographic hash implementations, accepts a byte array as its input. So the very first step is to serialize the data you want to hash.

This isn't as trivial as casting your struct to a byte array. Serialization should be portable between operating systems and hardware. Struct alignment, endianness, etc can vary between system, so it's best to use a serialization library, and leave all those tricky strict aliasing questions to the library authors.

Best Option: A Serialization Library

Since you already appear to be using Boost (the float64_t type), you can use the Boost serialization library. First, create a serialization function to instruct Boost how to serialize A:

namespace boost {
namespace serialization {

template<class Archive>
void serialize(Archive & ar, A & a, const unsigned int version)
{
    ar & a.array;
    ar & a.x;
    ar & a.y;
}

} // namespace serialization
} // namespace boost

Then, serialize it to an in-memory stream:

std::ostringstream plaintext_buffer {};
{
    boost::archive::binary_oarchive oa(plaintext_buffer);
    oa << a;
}
std::string plaintext = plaintext_buffer.str();

Now you can use your SHA-256 hash function. I'll leave that part as an exercise to you.

  • Input: plaintext.data() for data, and plaintext.size() for size
  • Output: a.validationHash

Good Option: custom floating point serializer

According to the comments, you're limited to C++03 (I'll take that as C++98), and can't use any libraries. So first, let's redefine your function using the closest equivalent standard types:

struct A
{
    double array[4][4];
    double x;
    double y;
    uint8_t validationHash[32]; // here computed hash need to be stored
}

I slightly adapted this answer: Serialize double and float with C , which claims to be a portable IEEE 754 serializer. Cool! I changed the output to a memory buffer, replaced goto, and converted C casts to static_cast.

void serializeIeee754(double x, uint8_t* destination)
{
    int                     shift;
    unsigned long           sign, exp, hibits, hilong, lowlong;
    double                  fnorm, significand;
    int                     expbits = 11;
    int                     significandbits = 52;

    if(x == 0) {
        /* zero (can't handle signed zero) */
        hilong = 0;
        lowlong = 0;
    } else if(x > DBL_MAX) {
        /* infinity */
        hilong = 1024 + ((1 << (expbits - 1)) - 1);
        hilong <<= (31 - expbits);
        lowlong = 0;
    } else if(x < -DBL_MAX) {
        /* -infinity */
        hilong = 1024 + ((1 << (expbits - 1)) - 1);
        hilong <<= (31 - expbits);
        hilong |= (1 << 31);
        lowlong = 0;
    } else if(x != x) {
        /* NaN - dodgy because many compilers optimise out this test
        * isnan() is C99, POSIX.1 only, use it if you will.
        */
        hilong = 1024 + ((1 << (expbits - 1)) - 1);
        hilong <<= (31 - expbits);
        lowlong = 1234;
    } else {
        /* get the sign */
        if(x < 0) {
            sign = 1;
            fnorm = -x;
        } else {
            sign = 0;
            fnorm = x;
        }

        /* get the normalized form of f and track the exponent */
        shift = 0;
        while(fnorm >= 2.0) {
            fnorm /= 2.0;
            shift++;
        }
        while(fnorm < 1.0) {
            fnorm *= 2.0;
            shift--;
        }

        /* check for denormalized numbers */
        if(shift < -1022) {
            while(shift < -1022) {
                fnorm /= 2.0;
                shift++;
            }
            shift = -1023;
        } else {
            /* take the significant bit off mantissa */
            fnorm = fnorm - 1.0;
        }
        /* calculate the integer form of the significand */
        /* hold it in a  double for now */

        significand = fnorm * ((1LL << significandbits) + 0.5f);

        /* get the biased exponent */
        exp = shift + ((1 << (expbits - 1)) - 1);   /* shift + bias */

        /* put the data into two longs */
        hibits = static_cast<long>(significand / 4294967296);  /* 0x100000000 */
        hilong = (sign << 31) | (exp << (31 - expbits)) | hibits;
        lowlong = static_cast<unsigned long>(significand - hibits * 4294967296);
    }

    destination[0] = lowlong & 0xFF;
    destination[1] = (lowlong >> 8) & 0xFF;
    destination[2] = (lowlong >> 16) & 0xFF;
    destination[3] = (lowlong >> 24) & 0xFF;
    destination[4] = hilong & 0xFF;
    destination[5] = (hilong >> 8) & 0xFF;
    destination[6] = (hilong >> 16) & 0xFF;
    destination[7] = (hilong >> 24) & 0xFF;
}

Now, you can write your own serializer for A that writes to a 144 byte buffer:

void serializeA(A& a, uint8_t destination[144]) {
    uint8_t* out = destination;
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            serializeIeee754(a.array[i][j], out);
            out += 8;
        }
    }
    serializeIeee754(a.x, out);
    out += 8;
    serializeIeee754(a.y, out);
}

Then supply that buffer to your hash function.

like image 164
parktomatomi Avatar answered Jan 20 '26 01:01

parktomatomi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!