Minimal HMAC-SHA256 implementation in C / C++ https://github.com/h5p9sl/hmac_sha256
Go to file
h5p9sl 79a57d2a85 Clean up code, add examples 2020-12-31 22:28:27 -07:00
examples Clean up code, add examples 2020-12-31 22:28:27 -07:00
README.md Clean up code, add examples 2020-12-31 22:28:27 -07:00
hmac_sha256.c Clean up code, add examples 2020-12-31 22:28:27 -07:00
hmac_sha256.h Clean up code, add examples 2020-12-31 22:28:27 -07:00
sha256.c Clean up code, add examples 2020-12-31 22:28:27 -07:00
sha256.h Clean up code, add examples 2020-12-31 22:28:27 -07:00

README.md

hmac_sha256

A SHA256 HMAC implementation in C/C++

Usage Example (C++)

#include "../hmac_sha256.h"

#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cassert>

#define SHA256_HASH_SIZE 32

int main() {
    const std::string str_data = "Hello World!";
    const std::string str_key = "super-secret-key";
    std::stringstream ss_result;

    // Allocate memory for the HMAC
    std::vector<uint8_t> out(SHA256_HASH_SIZE);

    // Call hmac-sha256 function
    hmac_sha256(
        str_key.data(),  str_key.size(),
        str_data.data(), str_data.size(),
        out.data(),  out.size()
    );

    // Convert `out` to string with std::hex
    for (uint8_t x : out) {
        ss_result << std::hex << std::setfill('0') << std::setw(2) << (int)x;
    }

    // Print out the result
    std::cout << "Message: " << str_data << std::endl;
    std::cout << "HMAC: " << ss_result.str() << std::endl;

    // This assertion fails if something went wrong
    assert(
        ss_result.str() ==
        "4b393abced1c497f8048860ba1ede46a23f1ff5209b18e9c428bddfbb690aad8"
    );
    return 0;
}