diff --git a/hmac.cpp b/hmac.cpp index 182296a..319ff8d 100644 --- a/hmac.cpp +++ b/hmac.cpp @@ -1,4 +1,5 @@ #include +#include #include "hmac.hpp" namespace hmac { @@ -82,6 +83,8 @@ namespace hmac { } std::vector get_hmac(const void* key_ptr, size_t key_len, const void* msg_ptr, size_t msg_len, TypeHash type) { + if ((key_len > 0 && key_ptr == nullptr) || (msg_len > 0 && msg_ptr == nullptr)) + throw std::invalid_argument("Null pointer with non-zero length"); size_t block_size = 0; size_t digest_size = 0; diff --git a/hmac.hpp b/hmac.hpp index 716d8c9..239d288 100644 --- a/hmac.hpp +++ b/hmac.hpp @@ -48,12 +48,13 @@ namespace hmac { } /// \brief Computes HMAC for raw binary data using the specified hash function. - /// \param key_ptr Pointer to the key buffer + /// \param key_ptr Pointer to the key buffer; must be non-null if key_len > 0 /// \param key_len Length of the key in bytes - /// \param msg_ptr Pointer to the message buffer + /// \param msg_ptr Pointer to the message buffer; must be non-null if msg_len > 0 /// \param msg_len Length of the message in bytes /// \param type Hash function type /// \return HMAC result as a vector of bytes + /// \throws std::invalid_argument If any pointer is null while the corresponding length is non-zero std::vector get_hmac(const void* key_ptr, size_t key_len, const void* msg_ptr, size_t msg_len, TypeHash type); /// \brief Computes HMAC from key and message byte vectors using the specified hash function diff --git a/test_all.cpp b/test_all.cpp index f257de8..91e8777 100644 --- a/test_all.cpp +++ b/test_all.cpp @@ -1,5 +1,6 @@ #include #include +#include #include "hmac.hpp" #include "hmac_utils.hpp" @@ -43,6 +44,13 @@ TEST(HMACTest, SHA512Uppercase) { "C54DDF9647A949D0DF925A1C1F8BA1C9D721A671C396FDE1062A71F9F7FFAE5DC10F6BE15BE63BB0363D051365E23F890368C54828497B9AEF2EB2FC65B633E6"); } +TEST(HMACTest, NullPointersThrow) { + const char* msg = "abc"; + EXPECT_THROW(hmac::get_hmac(nullptr, 1, msg, 3, hmac::TypeHash::SHA256), std::invalid_argument); + const char* key = "key"; + EXPECT_THROW(hmac::get_hmac(key, 3, nullptr, 1, hmac::TypeHash::SHA256), std::invalid_argument); +} + TEST(TOTPTest, AtTime) { const std::string totp_key = "12345678901234567890"; uint64_t test_time = 1234567890;