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;

No comments:

Post a Comment

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