Debian Codegraph @

lib/Crypto/Hash/Poly1305.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # Hash/Poly1305.py - Implements the Poly1305 MAC
4 #
5 # ===================================================================
6 # The contents of this file are dedicated to the public domain. To
7 # the extent that dedication to the public domain is not available,
8 # everyone is granted a worldwide, perpetual, royalty-free,
9 # non-exclusive license to exercise all rights associated with the
10 # contents of this file for any purpose whatsoever.
11 # No rights are reserved.
12 #
13 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
16 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
17 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
18 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 # SOFTWARE.
21 # ===================================================================
22
23 from binascii import unhexlify
24
25 from Crypto.Util.py3compat import bord, tobytes, _copy_bytes
26
27 from Crypto.Hash import BLAKE2s
28 from Crypto.Random import get_random_bytes
29 from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
30 VoidPointer, SmartPointer,
31 create_string_buffer,
32 get_raw_buffer, c_size_t,
33 c_uint8_ptr)
34
35
36 _raw_poly1305 = load_pycryptodome_raw_lib("Crypto.Hash._poly1305",
37 """
38 int poly1305_init(void **state,
39 const uint8_t *r,
40 size_t r_len,
41 const uint8_t *s,
42 size_t s_len);
43 int poly1305_destroy(void *state);
44 int poly1305_update(void *state,
45 const uint8_t *in,
46 size_t len);
47 int poly1305_digest(const void *state,
48 uint8_t *digest,
49 size_t len);
50 """)
51
52
53 class Poly1305_MAC(object):
54 """An Poly1305 MAC object.
55 Do not instantiate directly. Use the :func:`new` function.
56
57 :ivar digest_size: the size in bytes of the resulting MAC tag
58 :vartype digest_size: integer
59 """
60
61 digest_size = 16
62
63 def __init__(self, r, s, data):
64
65 if len(r) != 16:
66 raise ValueError("Parameter r is not 16 bytes long")
67 if len(s) != 16:
68 raise ValueError("Parameter s is not 16 bytes long")
69
70 self._mac_tag = None
71
72 state = VoidPointer()
73 result = _raw_poly1305.poly1305_init(state.address_of(),
74 c_uint8_ptr(r),
75 c_size_t(len(r)),
76 c_uint8_ptr(s),
77 c_size_t(len(s))
78 )
79 if result:
80 raise ValueError("Error %d while instantiating Poly1305" % result)
81 self._state = SmartPointer(state.get(),
82 _raw_poly1305.poly1305_destroy)
83 if data:
84 self.update(data)
85
86 def update(self, data):
87 """Authenticate the next chunk of message.
88
89 Args:
90 data (byte string/byte array/memoryview): The next chunk of data
91 """
92
93 if self._mac_tag:
94 raise TypeError("You can only call 'digest' or 'hexdigest' on this object")
95
96 result = _raw_poly1305.poly1305_update(self._state.get(),
97 c_uint8_ptr(data),
98 c_size_t(len(data)))
99 if result:
100 raise ValueError("Error %d while hashing Poly1305 data" % result)
101 return self
102
103 def copy(self):
104 raise NotImplementedError()
105
106 def digest(self):
107 """Return the **binary** (non-printable) MAC tag of the message
108 authenticated so far.
109
110 :return: The MAC tag digest, computed over the data processed so far.
111 Binary form.
112 :rtype: byte string
113 """
114
115 if self._mac_tag:
116 return self._mac_tag
117
118 bfr = create_string_buffer(16)
119 result = _raw_poly1305.poly1305_digest(self._state.get(),
120 bfr,
121 c_size_t(len(bfr)))
122 if result:
123 raise ValueError("Error %d while creating Poly1305 digest" % result)
124
125 self._mac_tag = get_raw_buffer(bfr)
126 return self._mac_tag
127
128 def hexdigest(self):
129 """Return the **printable** MAC tag of the message authenticated so far.
130
131 :return: The MAC tag, computed over the data processed so far.
132 Hexadecimal encoded.
133 :rtype: string
134 """
135
136 return "".join(["%02x" % bord(x)
137 for x in tuple(self.digest())])
138
139 def verify(self, mac_tag):
140 """Verify that a given **binary** MAC (computed by another party)
141 is valid.
142
143 Args:
144 mac_tag (byte string/byte string/memoryview): the expected MAC of the message.
145
146 Raises:
147 ValueError: if the MAC does not match. It means that the message
148 has been tampered with or that the MAC key is incorrect.
149 """
150
151 secret = get_random_bytes(16)
152
153 mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=mac_tag)
154 mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=self.digest())
155
156 if mac1.digest() != mac2.digest():
157 raise ValueError("MAC check failed")
158
159 def hexverify(self, hex_mac_tag):
160 """Verify that a given **printable** MAC (computed by another party)
161 is valid.
162
163 Args:
164 hex_mac_tag (string): the expected MAC of the message,
165 as a hexadecimal string.
166
167 Raises:
168 ValueError: if the MAC does not match. It means that the message
169 has been tampered with or that the MAC key is incorrect.
170 """
171
172 self.verify(unhexlify(tobytes(hex_mac_tag)))
173
174
175
176 def new(**kwargs):
177 """Create a new Poly1305 MAC object.
178
179 Args:
180 key (bytes/bytearray/memoryview):
181 The 32-byte key for the Poly1305 object.
182 cipher (module from ``Crypto.Cipher``):
183 The cipher algorithm to use for deriving the Poly1305
184 key pair *(r, s)*.
185 It can only be ``Crypto.Cipher.AES`` or ``Crypto.Cipher.ChaCha20``.
186 nonce (bytes/bytearray/memoryview):
187 Optional. The non-repeatable value to use for the MAC of this message.
188 It must be 16 bytes long for ``AES`` and 8 or 12 bytes for ``ChaCha20``.
189 If not passed, a random nonce is created; you will find it in the
190 ``nonce`` attribute of the new object.
191 data (bytes/bytearray/memoryview):
192 Optional. The very first chunk of the message to authenticate.
193 It is equivalent to an early call to ``update()``.
194
195 Returns:
196 A :class:`Poly1305_MAC` object
197 """
198
199 cipher = kwargs.pop("cipher", None)
200 if not hasattr(cipher, '_derive_Poly1305_key_pair'):
201 raise ValueError("Parameter 'cipher' must be AES or ChaCha20")
202
203 cipher_key = kwargs.pop("key", None)
204 if cipher_key is None:
205 raise TypeError("You must pass a parameter 'key'")
206
207 nonce = kwargs.pop("nonce", None)
208 data = kwargs.pop("data", None)
209
210 if kwargs:
211 raise TypeError("Unknown parameters: " + str(kwargs))
212
213 r, s, nonce = cipher._derive_Poly1305_key_pair(cipher_key, nonce)
214
215 new_mac = Poly1305_MAC(r, s, data)
216 new_mac.nonce = _copy_bytes(None, None, nonce) # nonce may still be just a memoryview
217 return new_mac