2019-07-05 02:25:55 +00:00
|
|
|
# [hmac_sha256](https://github.com/h5p9sl/hmac_sha256)
|
2021-01-01 05:24:10 +00:00
|
|
|
*A SHA256 HMAC implementation in C/C++*
|
2019-07-05 02:25:55 +00:00
|
|
|
|
2019-10-12 07:49:43 +00:00
|
|
|
## Usage Example (C++)
|
2019-07-05 02:25:55 +00:00
|
|
|
```cpp
|
2021-01-01 05:24:10 +00:00
|
|
|
#include "../hmac_sha256.h"
|
2019-07-05 02:25:55 +00:00
|
|
|
|
2019-07-08 06:12:02 +00:00
|
|
|
#include <vector>
|
|
|
|
#include <string>
|
2019-10-12 07:49:43 +00:00
|
|
|
#include <iostream>
|
|
|
|
#include <sstream>
|
2021-01-01 05:24:10 +00:00
|
|
|
#include <iomanip>
|
|
|
|
#include <cassert>
|
2019-10-12 07:49:43 +00:00
|
|
|
|
2021-01-01 05:24:10 +00:00
|
|
|
#define SHA256_HASH_SIZE 32
|
2019-07-05 02:25:55 +00:00
|
|
|
|
2019-10-12 07:49:43 +00:00
|
|
|
int main() {
|
2021-01-01 05:24:10 +00:00
|
|
|
const std::string str_data = "Hello World!";
|
|
|
|
const std::string str_key = "super-secret-key";
|
|
|
|
std::stringstream ss_result;
|
2019-10-12 07:49:43 +00:00
|
|
|
|
2021-01-01 05:24:10 +00:00
|
|
|
// Allocate memory for the HMAC
|
|
|
|
std::vector<uint8_t> out(SHA256_HASH_SIZE);
|
2019-07-05 02:25:55 +00:00
|
|
|
|
2020-01-16 06:21:00 +00:00
|
|
|
// Call hmac-sha256 function
|
2019-10-12 07:49:43 +00:00
|
|
|
hmac_sha256(
|
2021-01-01 05:24:10 +00:00
|
|
|
str_key.data(), str_key.size(),
|
|
|
|
str_data.data(), str_data.size(),
|
2019-10-12 07:49:43 +00:00
|
|
|
out.data(), out.size()
|
|
|
|
);
|
2019-07-05 02:25:55 +00:00
|
|
|
|
2020-01-16 06:21:00 +00:00
|
|
|
// Convert `out` to string with std::hex
|
2021-01-01 05:24:10 +00:00
|
|
|
for (uint8_t x : out) {
|
|
|
|
ss_result << std::hex << std::setfill('0') << std::setw(2) << (int)x;
|
2019-07-05 02:25:55 +00:00
|
|
|
}
|
|
|
|
|
2021-01-01 05:24:10 +00:00
|
|
|
// 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"
|
|
|
|
);
|
2019-07-05 02:25:55 +00:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
```
|
2021-01-01 05:32:35 +00:00
|
|
|
|
2021-01-01 05:38:03 +00:00
|
|
|
Thank you to the [WjCryptLib](https://github.com/WaterJuice/WjCryptLib) for providing the Sha256 implementation!
|