blob: 10dc0a72876b98fe3433c46155ae8475c4b683c4 [file] [log] [blame]
Yingdi Yud12fb972015-08-01 17:38:49 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
3 * Copyright (c) 2013-2016 Regents of the University of California.
4 *
5 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
6 *
7 * ndn-cxx library is free software: you can redistribute it and/or modify it under the
8 * terms of the GNU Lesser General Public License as published by the Free Software
9 * Foundation, either version 3 of the License, or (at your option) any later version.
10 *
11 * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
12 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
13 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
14 *
15 * You should have received copies of the GNU General Public License and GNU Lesser
16 * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
17 * <http://www.gnu.org/licenses/>.
18 *
19 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
20 */
21
22#include "hmac-filter.hpp"
23#include "../detail/openssl-helper.hpp"
24
25namespace ndn {
26namespace security {
27namespace transform {
28
29class HmacFilter::Impl
30{
31public:
32 Impl()
33 {
34 HMAC_CTX_init(&m_context);
35 }
36
37 ~Impl()
38 {
39 HMAC_CTX_cleanup(&m_context);
40 }
41
42public:
43 HMAC_CTX m_context;
44};
45
46HmacFilter::HmacFilter(DigestAlgorithm algo, const uint8_t* key, size_t keyLen)
47 : m_impl(new Impl)
48{
49 BOOST_ASSERT(key != nullptr);
50 BOOST_ASSERT(keyLen > 0);
51
52 const EVP_MD* algorithm = detail::toDigestEvpMd(algo);
53 if (algorithm == nullptr)
54 BOOST_THROW_EXCEPTION(Error(getIndex(), "Unsupported digest algorithm"));
55
56 if (HMAC_Init_ex(&m_impl->m_context, key, keyLen, algorithm, nullptr) == 0)
57 BOOST_THROW_EXCEPTION(Error(getIndex(), "Cannot initialize HMAC"));
58}
59
60size_t
61HmacFilter::convert(const uint8_t* buf, size_t size)
62{
63 if (HMAC_Update(&m_impl->m_context, buf, size) == 0)
64 BOOST_THROW_EXCEPTION(Error(getIndex(), "Failed to update HMAC"));
65
66 return size;
67}
68
69void
70HmacFilter::finalize()
71{
72 auto buffer = make_unique<OBuffer>(EVP_MAX_MD_SIZE);
73 unsigned int mdLen = 0;
74
75 if (HMAC_Final(&m_impl->m_context, &(*buffer)[0], &mdLen) == 0)
76 BOOST_THROW_EXCEPTION(Error(getIndex(), "Failed to finalize HMAC"));
77
78 buffer->erase(buffer->begin() + mdLen, buffer->end());
79 setOutputBuffer(std::move(buffer));
80
81 flushAllOutput();
82}
83
84unique_ptr<Transform>
85hmacFilter(DigestAlgorithm algo, const uint8_t* key, size_t keyLen)
86{
87 return make_unique<HmacFilter>(algo, key, keyLen);
88}
89
90} // namespace transform
91} // namespace security
92} // namespace ndn