Reputation: 1089
I was wondering if using union command to do a MD5 hash is recommended? the reason I want to use union is because I want do hash a structure like the following.
struct Body{
int commandType;
char data[MaxLine];
};
union UBody{
Body body;
char str[MaxLine + 4];
}
since #include <openssl/md5.h>
requires char type this is the only thing I could think of. please let me know.
Upvotes: 1
Views: 502
Reputation: 1
To compute the checksum of some in-memory data you could cast the pointer to that data to (char*)
and pass it to MD5
:
struct yourstruct_st data;
char md5[MD5_DIGEST_LENGTH];
MD5((const unsigned char*)&data, sizeof(data), md5);
Beware that the compiler can add padding to your struct
(or union
etc...) - and might not initialize the padding bytes. To have reproducible checksums, you need to be sure that all the bytes (including padding) of your memory zone are well defined. For example, if the zone is malloc
-ed you should zero all of it (with memset(ptr, 0, sizeof(*ptr));
) before filling it.
Of course the in-memory representation of some struct
is specific to your processor and ABI (and depends upon the endianness, etc...). So the in-memory MD5 can be different on different machines.
Upvotes: 2