NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.3: NDN, CCN, CCNx, content centric networks
API Documentation
signer-filter.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
22 #include "signer-filter.hpp"
23 #include "../../encoding/buffer.hpp"
24 #include "../detail/openssl.hpp"
25 
26 namespace ndn {
27 namespace security {
28 namespace transform {
29 
31 {
32 public:
33  Impl(const PrivateKey& key)
34  : m_key(key)
35  , m_md(BIO_new(BIO_f_md()))
36  , m_sink(BIO_new(BIO_s_null()))
37  {
38  BIO_push(m_md, m_sink);
39  }
40 
42  {
43  BIO_free_all(m_md);
44  }
45 
46 public:
47  const PrivateKey& m_key;
48 
49  BIO* m_md;
50  BIO* m_sink;
51 };
52 
54  : m_impl(new Impl(key))
55 {
56  switch (algo) {
58  if (!BIO_set_md(m_impl->m_md, EVP_sha256()))
59  BOOST_THROW_EXCEPTION(Error(getIndex(), "Cannot set digest"));
60  break;
61  }
62 
63  default:
64  BOOST_THROW_EXCEPTION(Error(getIndex(), "Digest algorithm is not supported"));
65  }
66 }
67 
68 size_t
69 SignerFilter::convert(const uint8_t* buf, size_t size)
70 {
71  int wLen = BIO_write(m_impl->m_md, buf, size);
72 
73  if (wLen <= 0) { // fail to write data
74  if (!BIO_should_retry(m_impl->m_md)) {
75  // we haven't written everything but some error happens, and we cannot retry
76  BOOST_THROW_EXCEPTION(Error(getIndex(), "Failed to accept more input"));
77  }
78  return 0;
79  }
80  else { // update number of bytes written
81  return wLen;
82  }
83 }
84 
85 void
86 SignerFilter::finalize()
87 {
88  EVP_PKEY* key = reinterpret_cast<EVP_PKEY*>(m_impl->m_key.getEvpPkey());
89  auto buffer = make_unique<OBuffer>(EVP_PKEY_size(key));
90  unsigned int sigLen = 0;
91 
92  EVP_MD_CTX* ctx = nullptr;
93  BIO_get_md_ctx(m_impl->m_md, &ctx);
94  EVP_SignFinal(ctx, &(*buffer)[0], &sigLen, key); // should be ok, enough space is allocated in buffer
95 
96  buffer->erase(buffer->begin() + sigLen, buffer->end());
97  setOutputBuffer(std::move(buffer));
98 
100 }
101 
102 unique_ptr<Transform>
104 {
105  return make_unique<SignerFilter>(algo, key);
106 }
107 
108 } // namespace transform
109 } // namespace security
110 } // namespace ndn
Copyright (c) 2011-2015 Regents of the University of California.
size_t getIndex() const
Get the module index.
void flushAllOutput()
Read the all the content from output buffer and write it into next module.
unique_ptr< Transform > signerFilter(DigestAlgorithm algo, const PrivateKey &key)
void setOutputBuffer(unique_ptr< OBuffer > buffer)
Set output buffer to buffer.
Abstraction of private key in crypto transformation.
Definition: private-key.hpp:38
Base class of transformation error.
SignerFilter(DigestAlgorithm algo, const PrivateKey &key)
Create a signer module to generate signature using algorithm algo and key.