Improve example code

This commit is contained in:
h5p9sl 2019-10-12 01:49:43 -06:00
parent fec119781d
commit a9cfd5e8f6
1 changed files with 20 additions and 17 deletions

View File

@ -1,35 +1,38 @@
# [hmac_sha256](https://github.com/h5p9sl/hmac_sha256) # [hmac_sha256](https://github.com/h5p9sl/hmac_sha256)
A SHA256 HMAC implementation in C/C++ A SHA256 HMAC implementation in C/C++
## Example (C++) ## Usage Example (C++)
```cpp ```cpp
#include "hmac_sha256.h" #include "hmac_sha256.h"
#include <iostream>
#include <sstream>
#include <vector> #include <vector>
#include <string> #include <string>
#include <cstring> #include <iostream>
#include <tuple> #include <sstream>
int main(void) { #define SHA256_HASHLEN 32
int main() {
const std::string testvector = "b0344c61d8db38535ca8afceafbf12b881dc20c9833da726e9376c2e32cff7"; const std::string testvector = "b0344c61d8db38535ca8afceafbf12b881dc20c9833da726e9376c2e32cff7";
const std::string str_data = "Hi There";
std::vector<uint8_t> key, data, out; std::vector<uint8_t> key, data, out;
std::stringstream result; std::stringstream result;
// Allocate memory // Allocate memory
key.resize(20); key.resize(20, 0x0b);
data.resize(8); data.resize(str_data.length(), 0);
out.resize(32); out.resize(SHA256_HASHLEN, 0);
// Initialize variables // Fill data
strncpy((char*)data.data(), "Hi There", data.size()); data.assign(str_data.cbegin(), str_data.cend());
memset(key.data(), 0x0b, key.size());
// Call hmac sha256 function // Call hmac sha256 function
hmac_sha256(key.data(), key.size(), hmac_sha256(
key.data(), key.size(),
data.data(), data.size(), data.data(), data.size(),
out.data(), out.size()); out.data(), out.size()
);
// Convert 'out' to string // Convert 'out' to string
for (unsigned i = 0; i < out.size(); i++) { for (unsigned i = 0; i < out.size(); i++) {
@ -41,9 +44,9 @@ int main(void) {
// Compare result // Compare result
if (testvector.compare(result.str()) == 0) { if (testvector.compare(result.str()) == 0) {
std::cout << "Test passed!" << std::endl; std::cout << "Test passed!" << std::endl;
return 0; } else {
}
std::cout << "Test failed." << std::endl; std::cout << "Test failed." << std::endl;
}
return 0; return 0;
} }