Created
March 21, 2018 15:25
-
-
Save ahamez/7fa5d9f378de3aa00d671544a1b9e9be to your computer and use it in GitHub Desktop.
HMAC with OpenSSL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iomanip> | |
| #include <iostream> | |
| #include <string> | |
| #include <vector> | |
| #include <openssl/hmac.h> | |
| int main() | |
| { | |
| // https://tools.ietf.org/html/rfc2104#section-3 | |
| // [...] L the byte-length of hash outputs (L=16 for MD5, L=20 for SHA-1) | |
| // [...] The key for HMAC can be of any length (keys longer than B bytes are first hashed using H). | |
| // However, less than L bytes is strongly discouraged as it would decrease the security strength of the function. | |
| // Keys longer than L bytes are acceptable but the extra length would not significantly increase the function strength. | |
| const auto key = std::string{"AVERYGOODKEYAVERYGOODKEYAVERYGOODKEY"}; | |
| const auto data = std::string{"DATA"}; | |
| auto digest = std::vector<unsigned char>(EVP_MAX_MD_SIZE); | |
| auto digest_len = std::uint32_t{0}; | |
| HMAC( | |
| EVP_sha1(), | |
| reinterpret_cast<const unsigned char*>(key.data()), key.size(), | |
| reinterpret_cast<const unsigned char*>(data.data()), data.size(), | |
| digest.data(), &digest_len | |
| ); | |
| // Decimal output. | |
| for (auto i = 0ul; i < digest_len; ++i) | |
| { | |
| std::cout << +digest[i] << ' '; | |
| } | |
| std::cout << '\n'; | |
| // Hexadecimal output. | |
| for (auto i = 0ul; i < digest_len; ++i) | |
| { | |
| std::cout << std::hex << std::setw(2) << std::setfill('0') << +digest[i] << ' '; | |
| } | |
| std::cout << '\n'; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment