Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- g++ test.cxx -o test -std=c++11 -lcrypto
- */
- #include <cstring>
- #include <ctime>
- #include <fstream>
- #include <functional>
- #include <iomanip>
- #include <iostream>
- #include <sstream>
- #include <string>
- #include "openssl/sha.h"
- std::string sha256_generic(const std::function<void(const void ** data, size_t * length)> & callback) {
- unsigned char hash[SHA256_DIGEST_LENGTH];
- SHA256_CTX ctx;
- SHA256_Init(&ctx);
- const void * data;
- size_t length;
- while (true) {
- callback(&data, &length);
- if (length == 0 || data == nullptr)
- break;
- SHA256_Update(&ctx, data, length);
- }
- SHA256_Final(hash, &ctx);
- std::ostringstream ostr;
- ostr << std::hex << std::setfill('0') << std::right;
- for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) {
- ostr << std::setw(2) << static_cast<int>(hash[i]);
- }
- return ostr.str();
- }
- std::string sha256_string(const std::string & str) {
- bool done = false;
- return sha256_generic(
- [&](const void ** data, size_t * length) {
- if (done) {
- *data = nullptr;
- *length = 0;
- } else {
- *data = static_cast<const void*>(str.c_str());
- *length = str.length();
- done = true;
- }
- } );
- }
- std::string sha256_file(const std::string & filename, size_t buffer_size = 65536) {
- std::ifstream ifile;
- ifile.open(filename, std::ios::in | std::ios::binary);
- if (! ifile.is_open()) {
- return "";
- }
- char * buffer = new char[buffer_size];
- return sha256_generic(
- [&](const void ** data, size_t * length) {
- std::streamsize read = ifile.readsome(buffer, static_cast<std::streamsize>(buffer_size));
- if (read > 0) {
- *data = buffer;
- *length = static_cast<size_t>(read);
- } else {
- *data = nullptr;
- *length = 0;
- delete [] buffer;
- ifile.close();
- }
- } );
- }
- int main(int argc, char* argv[]) {
- std::cout << sha256_string("") << std::endl;
- std::cout << sha256_string("Hello, World!") << std::endl;
- std::cout << sha256_file("test.cxx") << std::endl;
- std::cout << sha256_file("test") << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement