Vanetza
Loading...
Searching...
No Matches
hmac.cpp
1#include <vanetza/security/hmac.hpp>
2#include <algorithm>
3#include <array>
4
5#if defined VANETZA_WITH_OPENSSL
6#include <openssl/hmac.h>
7#endif
8
9#if defined VANETZA_WITH_CRYPTOPP
10#include <cryptopp/hmac.h>
11#include <cryptopp/sha.h>
12#endif
13
14namespace vanetza
15{
16namespace security
17{
18
19#if defined VANETZA_WITH_OPENSSL
20KeyTag create_hmac_tag_openssl(const ByteBuffer& data, const HmacKey& hmacKey)
21{
22 KeyTag keyTag;
23 std::array<std::uint8_t, EVP_MAX_MD_SIZE> tag;
24 unsigned int len = 0;
25 HMAC(EVP_sha256(), hmacKey.data(), static_cast<int>(hmacKey.size()),
26 data.data(), data.size(), tag.data(), &len);
27 std::copy_n(tag.data(), keyTag.size(), keyTag.data());
28 return keyTag;
29}
30#endif
31
32#if defined VANETZA_WITH_CRYPTOPP
33KeyTag create_hmac_tag_cryptopp(const ByteBuffer& data, const HmacKey& hmacKey)
34{
35 KeyTag keyTag;
36 std::array<std::uint8_t, 32> tag;
37 CryptoPP::HMAC<CryptoPP::SHA256> mac(hmacKey.data(), hmacKey.size());
38 mac.Update(data.data(), data.size());
39 mac.Final(tag.data());
40 std::copy_n(tag.data(), keyTag.size(), keyTag.data());
41 return keyTag;
42}
43#endif
44
45KeyTag create_hmac_tag(const ByteBuffer& data, const HmacKey& hmacKey)
46{
47#if defined VANETZA_WITH_OPENSSL
48 return create_hmac_tag_openssl(data, hmacKey);
49#elif defined VANETZA_WITH_CRYPTOPP
50 return create_hmac_tag_cryptopp(data, hmacKey);
51#else
52# warning "no HMAC implementation available"
53 return KeyTag {};
54#endif
55}
56
57} // namespace security
58} // namespace vanetza