aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/mac/poly1305/poly1305.cpp
blob: 8cf42abbb5ff6f58fa6a9cd9a2258ddbbde5d25e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
* Poly1305
* (C) 2014 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/mac_utils.h>
#include <botan/poly1305.h>
#include <botan/internal/poly1305_donna.h>

namespace Botan {

BOTAN_REGISTER_MAC_NOARGS(Poly1305);

void Poly1305::clear()
   {
   zap(m_poly);
   zap(m_buf);
   m_buf_pos = 0;
   }

void Poly1305::key_schedule(const byte key[], size_t)
   {
   m_buf_pos = 0;
   m_buf.resize(16);
   m_poly.resize(8);

   poly1305_init(m_poly, key);
   }

void Poly1305::add_data(const byte input[], size_t length)
   {
   BOTAN_ASSERT_EQUAL(m_poly.size(), 8, "Initialized");

   if(m_buf_pos)
      {
      buffer_insert(m_buf, m_buf_pos, input, length);

      if(m_buf_pos + length >= m_buf.size())
         {
         poly1305_blocks(m_poly, &m_buf[0], 1);
         input += (m_buf.size() - m_buf_pos);
         length -= (m_buf.size() - m_buf_pos);
         m_buf_pos = 0;
         }
      }

   const size_t full_blocks = length / m_buf.size();
   const size_t remaining   = length % m_buf.size();

   if(full_blocks)
      poly1305_blocks(m_poly, input, full_blocks);

   buffer_insert(m_buf, m_buf_pos, input + full_blocks * m_buf.size(), remaining);
   m_buf_pos += remaining;
   }

void Poly1305::final_result(byte out[])
   {
   BOTAN_ASSERT_EQUAL(m_poly.size(), 8, "Initialized");

   if(m_buf_pos != 0)
      {
      m_buf[m_buf_pos] = 1;
      clear_mem(&m_buf[m_buf_pos+1], m_buf.size() - m_buf_pos - 1);
      poly1305_blocks(m_poly, &m_buf[0], 1, true);
      }

   poly1305_finish(m_poly, out);

   m_poly.clear();
   m_buf_pos = 0;
   }

}