Thursday, February 03, 2022

[How To] Calculate hash of a vector in C++


This is a sample code to generate SHA256 in C++ using CryptoPP.

For the first string in a vector:
std::vector<std::string> stringVector{"abcde", "fghij", "klmno", "pqrst", "uvwxyz"};
byte digest[SHA256::DIGESTSIZE];
SHA256().CalculateDigest(digest, (const byte*)stringVector.data(), stringVector.size());
For an entire vector of string:
std::vector<std::string> stringVector{"abcde", "fghij", "klmno", "pqrst", "uvwxyz"};
HexEncoder encoder(new FileSink(std::cout));
std::string digest;
SHA256 hash;

for(auto str: stringVector) { 
hash.Update((const byte*)str.data(), str.size()); 


digest.resize(hash.DigestSize()); 
hash.Final((byte*)&digest[0]);

std::cout << "Digest: ";
StringSource(digest, true, new Redirector(encoder));
std::cout << std::endl;

This sample computes a SHA-256 hash in C++ with the Crypto++ library, applied to data held in a vector of strings. SHA-256 produces a fixed size digest that changes drastically with any change to the input.

Hashing is used for integrity checks, fingerprints, and lookups. Crypto++ is a mature C++ library that implements SHA-256 along with many other primitives.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.