Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions hmac.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include <algorithm>
#include <stdexcept>
#include <cstdint>
#include "hmac.hpp"

namespace hmac {
Expand Down Expand Up @@ -123,13 +124,17 @@ namespace hmac {
}

// Step 3: Compute inner hash
if (msg_len > SIZE_MAX - block_size)
throw std::overflow_error("msg_len + block_size overflow");
std::vector<uint8_t> inner_data;
inner_data.reserve(block_size + msg_len);
inner_data.insert(inner_data.end(), ikeypad.begin(), ikeypad.end());
inner_data.insert(inner_data.end(), reinterpret_cast<const uint8_t*>(msg_ptr), reinterpret_cast<const uint8_t*>(msg_ptr) + msg_len);
std::vector<uint8_t> inner_hash = get_hash(inner_data.data(), inner_data.size(), type);

// Step 4: Compute final HMAC
if (digest_size > SIZE_MAX - block_size)
throw std::overflow_error("digest_size + block_size overflow");
std::vector<uint8_t> outer_data;
outer_data.reserve(block_size + digest_size);
outer_data.insert(outer_data.end(), okeypad.begin(), okeypad.end());
Expand Down
9 changes: 9 additions & 0 deletions test_all.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,15 @@ TEST(HMACTest, InvalidTypeThrows) {
EXPECT_THROW(hmac::get_hmac(key, 3, msg, 3, invalid), std::invalid_argument);
}

TEST(HMACTest, MsgLenOverflowThrows) {
const char key[] = "key";
const char msg[] = "a";
size_t huge_len = std::numeric_limits<size_t>::max() -
hmac_hash::SHA256::SHA224_256_BLOCK_SIZE + 1;
EXPECT_THROW(hmac::get_hmac(key, sizeof(key) - 1, msg, huge_len,
hmac::TypeHash::SHA256), std::overflow_error);
}

TEST(HMACTest, InvalidTypeThrowsString) {
const std::string key = "key";
const std::string msg = "abc";
Expand Down
Loading