Skip to content

Instantly share code, notes, and snippets.

@jhasse
Last active October 6, 2023 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhasse/2c0b64f38d1d7826d465ed0d63a27da9 to your computer and use it in GitHub Desktop.
Save jhasse/2c0b64f38d1d7826d465ed0d63a27da9 to your computer and use it in GitHub Desktop.
Create SHA1 with Boost
#include <boost/uuid/detail/sha1.hpp>
#include <iomanip>
#include <iostream>
#include <sstream>
std::string sha1(const std::string& input) {
boost::uuids::detail::sha1 sha1;
sha1.process_bytes(input.data(), input.size());
unsigned int digest[5];
sha1.get_digest(digest);
std::ostringstream hash;
hash << std::hex << std::setfill('0');
for (size_t i = 0; i < 5; ++i) {
// Swap byte order because of Little Endian
const char* tmp = reinterpret_cast<char*>(digest);
hash << std::setw(2) << static_cast<int>(static_cast<uint8_t>(tmp[i * 4 + 3]))
<< std::setw(2) << static_cast<int>(static_cast<uint8_t>(tmp[i * 4 + 2]))
<< std::setw(2) << static_cast<int>(static_cast<uint8_t>(tmp[i * 4 + 1]))
<< std::setw(2) << static_cast<int>(static_cast<uint8_t>(tmp[i * 4]));
}
return hash.str();
}
int main() {
std::cout << sha1("hello world") << std::endl;
// output: 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment