Home > Blockchain >  Cryptographically hash multiple keys
Cryptographically hash multiple keys

Time:03-20

How to hash using SHA1(or similar cryptogrphical functions) a class(or struct) which has multiple keys, e.g.,

struct Foo{
   string name;
   int age;
   int score;
}

A naive approach is hash(has(name) hash(age) hash(score)), but hash collision is possible.

CodePudding user response:

Either hash the whole structure directly if it contains only POD (i.e. nothing allocated within and its sizeof is a constant): either you can use an union to get a proper byte array, or you use a cast to obtain a char* to provide to hash function.

If you have dynamic data inside your struct/class, you need to serialize all data and send them to the hash function - obviously, its size will vary during execution, because of dynamic data. But you must call hash only ONCE per data structure, and in NO WAY adding hashes together - that's a nonsense. You can also use a framework feature that will serialize your struct/class to a text stream (often XML or JSON format), and hash this serialization instead of the binary structure.

How to do all this is obviously platform-dependent - which cryptography API do you use, if you prefer.

By applying these principles, the collision (totally unavoidable, mathematically proven) won't be more than for any other kind of hashed data.

  • Related