Debian Codegraph @

lib/Crypto/Signature/eddsa.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2022, Legrandin <[email protected]>
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29 # ===================================================================
30
31 from Crypto.Math.Numbers import Integer
32
33 from Crypto.Hash import SHA512, SHAKE256
34 from Crypto.Util.py3compat import bchr, is_bytes
35 from Crypto.PublicKey.ECC import (EccKey,
36 construct,
37 _import_ed25519_public_key,
38 _import_ed448_public_key)
39
40
41 def import_public_key(encoded):
42 """Create a new Ed25519 or Ed448 public key object,
43 starting from the key encoded as raw ``bytes``,
44 in the format described in RFC8032.
45
46 Args:
47 encoded (bytes):
48 The EdDSA public key to import.
49 It must be 32 bytes for Ed25519, and 57 bytes for Ed448.
50
51 Returns:
52 :class:`Crypto.PublicKey.EccKey` : a new ECC key object.
53
54 Raises:
55 ValueError: when the given key cannot be parsed.
56 """
57
58 if len(encoded) == 32:
59 x, y = _import_ed25519_public_key(encoded)
60 curve_name = "Ed25519"
61 elif len(encoded) == 57:
62 x, y = _import_ed448_public_key(encoded)
63 curve_name = "Ed448"
64 else:
65 raise ValueError("Not an EdDSA key (%d bytes)" % len(encoded))
66 return construct(curve=curve_name, point_x=x, point_y=y)
67
68
69 def import_private_key(encoded):
70 """Create a new Ed25519 or Ed448 private key object,
71 starting from the key encoded as raw ``bytes``,
72 in the format described in RFC8032.
73
74 Args:
75 encoded (bytes):
76 The EdDSA private key to import.
77 It must be 32 bytes for Ed25519, and 57 bytes for Ed448.
78
79 Returns:
80 :class:`Crypto.PublicKey.EccKey` : a new ECC key object.
81
82 Raises:
83 ValueError: when the given key cannot be parsed.
84 """
85
86 if len(encoded) == 32:
87 curve_name = "ed25519"
88 elif len(encoded) == 57:
89 curve_name = "ed448"
90 else:
91 raise ValueError("Incorrect length. Only EdDSA private keys are supported.")
92
93 # Note that the private key is truly a sequence of random bytes,
94 # so we cannot check its correctness in any way.
95
96 return construct(seed=encoded, curve=curve_name)
97
98
99 class EdDSASigScheme(object):
100 """An EdDSA signature object.
101 Do not instantiate directly.
102 Use :func:`Crypto.Signature.eddsa.new`.
103 """
104
105 def __init__(self, key, context):
106 """Create a new EdDSA object.
107
108 Do not instantiate this object directly,
109 use `Crypto.Signature.DSS.new` instead.
110 """
111
112 self._key = key
113 self._context = context
114 self._A = key._export_eddsa()
115 self._order = key._curve.order
116
117 def can_sign(self):
118 """Return ``True`` if this signature object can be used
119 for signing messages."""
120
121 return self._key.has_private()
122
123 def sign(self, msg_or_hash):
124 """Compute the EdDSA signature of a message.
125
126 Args:
127 msg_or_hash (bytes or a hash object):
128 The message to sign (``bytes``, in case of *PureEdDSA*) or
129 the hash that was carried out over the message (hash object, for *HashEdDSA*).
130
131 The hash object must be :class:`Crypto.Hash.SHA512` for Ed25519,
132 and :class:`Crypto.Hash.SHAKE256` object for Ed448.
133
134 :return: The signature as ``bytes``. It is always 64 bytes for Ed25519, and 114 bytes for Ed448.
135 :raise TypeError: if the EdDSA key has no private half
136 """
137
138 if not self._key.has_private():
139 raise TypeError("Private key is needed to sign")
140
141 if self._key._curve.name == "ed25519":
142 ph = isinstance(msg_or_hash, SHA512.SHA512Hash)
143 if not (ph or is_bytes(msg_or_hash)):
144 raise TypeError("'msg_or_hash' must be bytes of a SHA-512 hash")
145 eddsa_sign_method = self._sign_ed25519
146
147 elif self._key._curve.name == "ed448":
148 ph = isinstance(msg_or_hash, SHAKE256.SHAKE256_XOF)
149 if not (ph or is_bytes(msg_or_hash)):
150 raise TypeError("'msg_or_hash' must be bytes of a SHAKE256 hash")
151 eddsa_sign_method = self._sign_ed448
152
153 else:
154 raise ValueError("Incorrect curve for EdDSA")
155
156 return eddsa_sign_method(msg_or_hash, ph)
157
158 def _sign_ed25519(self, msg_or_hash, ph):
159
160 if self._context or ph:
161 flag = int(ph)
162 # dom2(flag, self._context)
163 dom2 = b'SigEd25519 no Ed25519 collisions' + bchr(flag) + \
164 bchr(len(self._context)) + self._context
165 else:
166 dom2 = b''
167
168 PHM = msg_or_hash.digest() if ph else msg_or_hash
169
170 # See RFC 8032, section 5.1.6
171
172 # Step 2
173 r_hash = SHA512.new(dom2 + self._key._prefix + PHM).digest()
174 r = Integer.from_bytes(r_hash, 'little') % self._order
175 # Step 3
176 R_pk = EccKey(point=r * self._key._curve.G)._export_eddsa()
177 # Step 4
178 k_hash = SHA512.new(dom2 + R_pk + self._A + PHM).digest()
179 k = Integer.from_bytes(k_hash, 'little') % self._order
180 # Step 5
181 s = (r + k * self._key.d) % self._order
182
183 return R_pk + s.to_bytes(32, 'little')
184
185 def _sign_ed448(self, msg_or_hash, ph):
186
187 flag = int(ph)
188 # dom4(flag, self._context)
189 dom4 = b'SigEd448' + bchr(flag) + \
190 bchr(len(self._context)) + self._context
191
192 PHM = msg_or_hash.read(64) if ph else msg_or_hash
193
194 # See RFC 8032, section 5.2.6
195
196 # Step 2
197 r_hash = SHAKE256.new(dom4 + self._key._prefix + PHM).read(114)
198 r = Integer.from_bytes(r_hash, 'little') % self._order
199 # Step 3
200 R_pk = EccKey(point=r * self._key._curve.G)._export_eddsa()
201 # Step 4
202 k_hash = SHAKE256.new(dom4 + R_pk + self._A + PHM).read(114)
203 k = Integer.from_bytes(k_hash, 'little') % self._order
204 # Step 5
205 s = (r + k * self._key.d) % self._order
206
207 return R_pk + s.to_bytes(57, 'little')
208
209 def verify(self, msg_or_hash, signature):
210 """Check if an EdDSA signature is authentic.
211
212 Args:
213 msg_or_hash (bytes or a hash object):
214 The message to verify (``bytes``, in case of *PureEdDSA*) or
215 the hash that was carried out over the message (hash object, for *HashEdDSA*).
216
217 The hash object must be :class:`Crypto.Hash.SHA512` object for Ed25519,
218 and :class:`Crypto.Hash.SHAKE256` for Ed448.
219
220 signature (``bytes``):
221 The signature that needs to be validated.
222 It must be 64 bytes for Ed25519, and 114 bytes for Ed448.
223
224 :raise ValueError: if the signature is not authentic
225 """
226
227 if self._key._curve.name == "ed25519":
228 ph = isinstance(msg_or_hash, SHA512.SHA512Hash)
229 if not (ph or is_bytes(msg_or_hash)):
230 raise TypeError("'msg_or_hash' must be bytes of a SHA-512 hash")
231 eddsa_verify_method = self._verify_ed25519
232
233 elif self._key._curve.name == "ed448":
234 ph = isinstance(msg_or_hash, SHAKE256.SHAKE256_XOF)
235 if not (ph or is_bytes(msg_or_hash)):
236 raise TypeError("'msg_or_hash' must be bytes of a SHAKE256 hash")
237 eddsa_verify_method = self._verify_ed448
238
239 else:
240 raise ValueError("Incorrect curve for EdDSA")
241
242 return eddsa_verify_method(msg_or_hash, signature, ph)
243
244 def _verify_ed25519(self, msg_or_hash, signature, ph):
245
246 if len(signature) != 64:
247 raise ValueError("The signature is not authentic (length)")
248
249 if self._context or ph:
250 flag = int(ph)
251 dom2 = b'SigEd25519 no Ed25519 collisions' + bchr(flag) + \
252 bchr(len(self._context)) + self._context
253 else:
254 dom2 = b''
255
256 PHM = msg_or_hash.digest() if ph else msg_or_hash
257
258 # Section 5.1.7
259
260 # Step 1
261 try:
262 R = import_public_key(signature[:32]).pointQ
263 except ValueError:
264 raise ValueError("The signature is not authentic (R)")
265 s = Integer.from_bytes(signature[32:], 'little')
266 if s > self._order:
267 raise ValueError("The signature is not authentic (S)")
268 # Step 2
269 k_hash = SHA512.new(dom2 + signature[:32] + self._A + PHM).digest()
270 k = Integer.from_bytes(k_hash, 'little') % self._order
271 # Step 3
272 point1 = s * 8 * self._key._curve.G
273 # OPTIMIZE: with double-scalar multiplication, with no SCA
274 # countermeasures because it is public values
275 point2 = 8 * R + k * 8 * self._key.pointQ
276 if point1 != point2:
277 raise ValueError("The signature is not authentic")
278
279 def _verify_ed448(self, msg_or_hash, signature, ph):
280
281 if len(signature) != 114:
282 raise ValueError("The signature is not authentic (length)")
283
284 flag = int(ph)
285 # dom4(flag, self._context)
286 dom4 = b'SigEd448' + bchr(flag) + \
287 bchr(len(self._context)) + self._context
288
289 PHM = msg_or_hash.read(64) if ph else msg_or_hash
290
291 # Section 5.2.7
292
293 # Step 1
294 try:
295 R = import_public_key(signature[:57]).pointQ
296 except ValueError:
297 raise ValueError("The signature is not authentic (R)")
298 s = Integer.from_bytes(signature[57:], 'little')
299 if s > self._order:
300 raise ValueError("The signature is not authentic (S)")
301 # Step 2
302 k_hash = SHAKE256.new(dom4 + signature[:57] + self._A + PHM).read(114)
303 k = Integer.from_bytes(k_hash, 'little') % self._order
304 # Step 3
305 point1 = s * 8 * self._key._curve.G
306 # OPTIMIZE: with double-scalar multiplication, with no SCA
307 # countermeasures because it is public values
308 point2 = 8 * R + k * 8 * self._key.pointQ
309 if point1 != point2:
310 raise ValueError("The signature is not authentic")
311
312
313 def new(key, mode, context=None):
314 """Create a signature object :class:`EdDSASigScheme` that
315 can perform or verify an EdDSA signature.
316
317 Args:
318 key (:class:`Crypto.PublicKey.ECC` object):
319 The key to use for computing the signature (*private* keys only)
320 or for verifying one.
321 The key must be on the curve ``Ed25519`` or ``Ed448``.
322
323 mode (string):
324 This parameter must be ``'rfc8032'``.
325
326 context (bytes):
327 Up to 255 bytes of `context <https://datatracker.ietf.org/doc/html/rfc8032#page-41>`_,
328 which is a constant byte string to segregate different protocols or
329 different applications of the same key.
330 """
331
332 if not isinstance(key, EccKey) or not key._is_eddsa():
333 raise ValueError("EdDSA can only be used with EdDSA keys")
334
335 if mode != 'rfc8032':
336 raise ValueError("Mode must be 'rfc8032'")
337
338 if context is None:
339 context = b''
340 elif len(context) > 255:
341 raise ValueError("Context for EdDSA must not be longer than 255 bytes")
342
343 return EdDSASigScheme(key, context)