NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.3: NDN, CCN, CCNx, content centric networks
API Documentation
hmac-filter.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
22 #include "hmac-filter.hpp"
23 #include "../detail/openssl-helper.hpp"
24 
25 namespace ndn {
26 namespace security {
27 namespace transform {
28 
30 {
31 public:
32 #if OPENSSL_VERSION_NUMBER < 0x1010000fL
33  Impl()
34  {
35  HMAC_CTX_init(&m_context);
36  }
37 
39  {
40  HMAC_CTX_cleanup(&m_context);
41  }
42 
43  operator HMAC_CTX*()
44  {
45  return &m_context;
46  }
47 
48 private:
49  HMAC_CTX m_context;
50 #else
51  Impl()
52  : m_context(HMAC_CTX_new())
53  {
54  }
55 
56  ~Impl()
57  {
58  HMAC_CTX_free(m_context);
59  }
60 
61  operator HMAC_CTX*()
62  {
63  return m_context;
64  }
65 
66 private:
67  HMAC_CTX* m_context;
68 #endif // OPENSSL_VERSION_NUMBER < 0x1010000fL
69 };
70 
71 HmacFilter::HmacFilter(DigestAlgorithm algo, const uint8_t* key, size_t keyLen)
72  : m_impl(new Impl)
73 {
74  BOOST_ASSERT(key != nullptr);
75  BOOST_ASSERT(keyLen > 0);
76 
77  const EVP_MD* algorithm = detail::toDigestEvpMd(algo);
78  if (algorithm == nullptr)
79  BOOST_THROW_EXCEPTION(Error(getIndex(), "Unsupported digest algorithm"));
80 
81  if (HMAC_Init_ex(*m_impl, key, keyLen, algorithm, nullptr) == 0)
82  BOOST_THROW_EXCEPTION(Error(getIndex(), "Cannot initialize HMAC"));
83 }
84 
85 size_t
86 HmacFilter::convert(const uint8_t* buf, size_t size)
87 {
88  if (HMAC_Update(*m_impl, buf, size) == 0)
89  BOOST_THROW_EXCEPTION(Error(getIndex(), "Failed to update HMAC"));
90 
91  return size;
92 }
93 
94 void
95 HmacFilter::finalize()
96 {
97  auto buffer = make_unique<OBuffer>(EVP_MAX_MD_SIZE);
98  unsigned int mdLen = 0;
99 
100  if (HMAC_Final(*m_impl, &(*buffer)[0], &mdLen) == 0)
101  BOOST_THROW_EXCEPTION(Error(getIndex(), "Failed to finalize HMAC"));
102 
103  buffer->erase(buffer->begin() + mdLen, buffer->end());
104  setOutputBuffer(std::move(buffer));
105 
106  flushAllOutput();
107 }
108 
109 unique_ptr<Transform>
110 hmacFilter(DigestAlgorithm algo, const uint8_t* key, size_t keyLen)
111 {
112  return make_unique<HmacFilter>(algo, key, keyLen);
113 }
114 
115 } // namespace transform
116 } // namespace security
117 } // namespace ndn
Copyright (c) 2011-2015 Regents of the University of California.
size_t getIndex() const
Get the module index.
unique_ptr< Transform > hmacFilter(DigestAlgorithm algo, const uint8_t *key, size_t keyLen)
void flushAllOutput()
Read the all the content from output buffer and write it into next module.
void setOutputBuffer(unique_ptr< OBuffer > buffer)
Set output buffer to buffer.
Base class of transformation error.
HmacFilter(DigestAlgorithm algo, const uint8_t *key, size_t keyLen)
Create a HMAC module to generate HMAC using algorithm algo and key.
Definition: hmac-filter.cpp:71
const EVP_MD * toDigestEvpMd(DigestAlgorithm algo)