2019-07-05 02:25:55 +00:00
|
|
|
# [hmac_sha256](https://github.com/h5p9sl/hmac_sha256)
|
|
|
|
A SHA256 HMAC implementation in C/C++
|
|
|
|
|
2019-10-12 07:49:43 +00:00
|
|
|
## Usage Example (C++)
|
2019-07-05 02:25:55 +00:00
|
|
|
```cpp
|
|
|
|
#include "hmac_sha256.h"
|
|
|
|
|
2019-07-08 06:12:02 +00:00
|
|
|
#include <vector>
|
|
|
|
#include <string>
|
2019-10-12 07:49:43 +00:00
|
|
|
#include <iostream>
|
|
|
|
#include <sstream>
|
|
|
|
|
|
|
|
#define SHA256_HASHLEN 32
|
2019-07-05 02:25:55 +00:00
|
|
|
|
2019-10-12 07:49:43 +00:00
|
|
|
int main() {
|
2019-07-08 06:12:02 +00:00
|
|
|
const std::string testvector = "b0344c61d8db38535ca8afceafbf12b881dc20c9833da726e9376c2e32cff7";
|
2019-10-12 07:49:43 +00:00
|
|
|
const std::string str_data = "Hi There";
|
|
|
|
|
2019-10-12 07:26:14 +00:00
|
|
|
std::vector<uint8_t> key, data, out;
|
2019-07-05 02:25:55 +00:00
|
|
|
std::stringstream result;
|
|
|
|
|
|
|
|
// Allocate memory
|
2019-10-12 07:49:43 +00:00
|
|
|
key.resize(20, 0x0b);
|
|
|
|
data.resize(str_data.length(), 0);
|
|
|
|
out.resize(SHA256_HASHLEN, 0);
|
2019-07-05 02:25:55 +00:00
|
|
|
|
2019-10-12 07:49:43 +00:00
|
|
|
// Fill data
|
|
|
|
data.assign(str_data.cbegin(), str_data.cend());
|
2019-07-05 02:25:55 +00:00
|
|
|
|
2019-07-08 06:12:02 +00:00
|
|
|
// Call hmac sha256 function
|
2019-10-12 07:49:43 +00:00
|
|
|
hmac_sha256(
|
|
|
|
key.data(), key.size(),
|
|
|
|
data.data(), data.size(),
|
|
|
|
out.data(), out.size()
|
|
|
|
);
|
2019-07-05 02:25:55 +00:00
|
|
|
|
|
|
|
// Convert 'out' to string
|
2019-07-08 06:12:02 +00:00
|
|
|
for (unsigned i = 0; i < out.size(); i++) {
|
2019-07-05 02:25:55 +00:00
|
|
|
result << std::hex << (int)out[i];
|
|
|
|
}
|
|
|
|
std::cout << result.str() << std::endl;
|
|
|
|
std::cout << testvector << std::endl;
|
|
|
|
|
|
|
|
// Compare result
|
2019-07-08 06:12:02 +00:00
|
|
|
if (testvector.compare(result.str()) == 0) {
|
2019-07-05 02:25:55 +00:00
|
|
|
std::cout << "Test passed!" << std::endl;
|
2019-10-12 07:49:43 +00:00
|
|
|
} else {
|
|
|
|
std::cout << "Test failed." << std::endl;
|
2019-07-05 02:25:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
```
|