Debian Codegraph @

lib/Crypto/PublicKey/ECC.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2015, 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 __future__ import print_function
32
33 import re
34 import struct
35 import binascii
36 from collections import namedtuple
37
38 from Crypto.Util.py3compat import bord, tobytes, tostr, bchr, is_string
39 from Crypto.Util.number import bytes_to_long, long_to_bytes
40
41 from Crypto.Math.Numbers import Integer
42 from Crypto.Util.asn1 import (DerObjectId, DerOctetString, DerSequence,
43 DerBitString)
44
45 from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
46 SmartPointer, c_size_t, c_uint8_ptr,
47 c_ulonglong, null_pointer)
48
49 from Crypto.PublicKey import (_expand_subject_public_key_info,
50 _create_subject_public_key_info,
51 _extract_subject_public_key_info)
52
53 from Crypto.Hash import SHA512, SHAKE256
54
55 from Crypto.Random import get_random_bytes
56 from Crypto.Random.random import getrandbits
57
58
59 _ec_lib = load_pycryptodome_raw_lib("Crypto.PublicKey._ec_ws", """
60 typedef void EcContext;
61 typedef void EcPoint;
62 int ec_ws_new_context(EcContext **pec_ctx,
63 const uint8_t *modulus,
64 const uint8_t *b,
65 const uint8_t *order,
66 size_t len,
67 uint64_t seed);
68 void ec_free_context(EcContext *ec_ctx);
69 int ec_ws_new_point(EcPoint **pecp,
70 const uint8_t *x,
71 const uint8_t *y,
72 size_t len,
73 const EcContext *ec_ctx);
74 void ec_ws_free_point(EcPoint *ecp);
75 int ec_ws_get_xy(uint8_t *x,
76 uint8_t *y,
77 size_t len,
78 const EcPoint *ecp);
79 int ec_ws_double(EcPoint *p);
80 int ec_ws_add(EcPoint *ecpa, EcPoint *ecpb);
81 int ec_ws_scalar(EcPoint *ecp,
82 const uint8_t *k,
83 size_t len,
84 uint64_t seed);
85 int ec_ws_clone(EcPoint **pecp2, const EcPoint *ecp);
86 int ec_ws_cmp(const EcPoint *ecp1, const EcPoint *ecp2);
87 int ec_ws_neg(EcPoint *p);
88 """)
89
90 _ed25519_lib = load_pycryptodome_raw_lib("Crypto.PublicKey._ed25519", """
91 typedef void Point;
92 int ed25519_new_point(Point **out,
93 const uint8_t x[32],
94 const uint8_t y[32],
95 size_t modsize,
96 const void *context);
97 int ed25519_clone(Point **P, const Point *Q);
98 void ed25519_free_point(Point *p);
99 int ed25519_cmp(const Point *p1, const Point *p2);
100 int ed25519_neg(Point *p);
101 int ed25519_get_xy(uint8_t *xb, uint8_t *yb, size_t modsize, Point *p);
102 int ed25519_double(Point *p);
103 int ed25519_add(Point *P1, const Point *P2);
104 int ed25519_scalar(Point *P, const uint8_t *scalar, size_t scalar_len, uint64_t seed);
105 """)
106
107 _ed448_lib = load_pycryptodome_raw_lib("Crypto.PublicKey._ed448", """
108 typedef void EcContext;
109 typedef void PointEd448;
110 int ed448_new_context(EcContext **pec_ctx);
111 void ed448_context(EcContext *ec_ctx);
112 void ed448_free_context(EcContext *ec_ctx);
113 int ed448_new_point(PointEd448 **out,
114 const uint8_t x[56],
115 const uint8_t y[56],
116 size_t len,
117 const EcContext *context);
118 int ed448_clone(PointEd448 **P, const PointEd448 *Q);
119 void ed448_free_point(PointEd448 *p);
120 int ed448_cmp(const PointEd448 *p1, const PointEd448 *p2);
121 int ed448_neg(PointEd448 *p);
122 int ed448_get_xy(uint8_t *xb, uint8_t *yb, size_t len, const PointEd448 *p);
123 int ed448_double(PointEd448 *p);
124 int ed448_add(PointEd448 *P1, const PointEd448 *P2);
125 int ed448_scalar(PointEd448 *P, const uint8_t *scalar, size_t scalar_len, uint64_t seed);
126 """)
127
128
129 def lib_func(ecc_obj, func_name):
130 if ecc_obj._curve.desc == "Ed25519":
131 result = getattr(_ed25519_lib, "ed25519_" + func_name)
132 elif ecc_obj._curve.desc == "Ed448":
133 result = getattr(_ed448_lib, "ed448_" + func_name)
134 else:
135 result = getattr(_ec_lib, "ec_ws_" + func_name)
136 return result
137
138 #
139 # _curves is a database of curve parameters. Items are indexed by their
140 # human-friendly name, suchas "P-256". Each item has the following fields:
141 # - p: the prime number that defines the finite field for all modulo operations
142 # - b: the constant in the Short Weierstrass curve equation
143 # - order: the number of elements in the group with the generator below
144 # - Gx the affine coordinate X of the generator point
145 # - Gy the affine coordinate Y of the generator point
146 # - G the generator, as an EccPoint object
147 # - modulus_bits the minimum number of bits for encoding the modulus p
148 # - oid an ASCII string with the registered ASN.1 Object ID
149 # - context a raw pointer to memory holding a context for all curve operations (can be NULL)
150 # - desc an ASCII string describing the curve
151 # - openssh the ASCII string used in OpenSSH id files for public keys on this curve
152 # - name the ASCII string which is also a valid key in _curves
153
154
155 _Curve = namedtuple("_Curve", "p b order Gx Gy G modulus_bits oid context desc openssh name")
156 _curves = {}
157
158
159 p192_names = ["p192", "NIST P-192", "P-192", "prime192v1", "secp192r1",
160 "nistp192"]
161
162
163 def init_p192():
164 p = 0xfffffffffffffffffffffffffffffffeffffffffffffffff
165 b = 0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1
166 order = 0xffffffffffffffffffffffff99def836146bc9b1b4d22831
167 Gx = 0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012
168 Gy = 0x07192b95ffc8da78631011ed6b24cdd573f977a11e794811
169
170 p192_modulus = long_to_bytes(p, 24)
171 p192_b = long_to_bytes(b, 24)
172 p192_order = long_to_bytes(order, 24)
173
174 ec_p192_context = VoidPointer()
175 result = _ec_lib.ec_ws_new_context(ec_p192_context.address_of(),
176 c_uint8_ptr(p192_modulus),
177 c_uint8_ptr(p192_b),
178 c_uint8_ptr(p192_order),
179 c_size_t(len(p192_modulus)),
180 c_ulonglong(getrandbits(64))
181 )
182 if result:
183 raise ImportError("Error %d initializing P-192 context" % result)
184
185 context = SmartPointer(ec_p192_context.get(), _ec_lib.ec_free_context)
186 p192 = _Curve(Integer(p),
187 Integer(b),
188 Integer(order),
189 Integer(Gx),
190 Integer(Gy),
191 None,
192 192,
193 "1.2.840.10045.3.1.1", # ANSI X9.62 / SEC2
194 context,
195 "NIST P-192",
196 "ecdsa-sha2-nistp192",
197 "p192")
198 global p192_names
199 _curves.update(dict.fromkeys(p192_names, p192))
200
201
202 init_p192()
203 del init_p192
204
205
206 p224_names = ["p224", "NIST P-224", "P-224", "prime224v1", "secp224r1",
207 "nistp224"]
208
209
210 def init_p224():
211 p = 0xffffffffffffffffffffffffffffffff000000000000000000000001
212 b = 0xb4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4
213 order = 0xffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d
214 Gx = 0xb70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21
215 Gy = 0xbd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34
216
217 p224_modulus = long_to_bytes(p, 28)
218 p224_b = long_to_bytes(b, 28)
219 p224_order = long_to_bytes(order, 28)
220
221 ec_p224_context = VoidPointer()
222 result = _ec_lib.ec_ws_new_context(ec_p224_context.address_of(),
223 c_uint8_ptr(p224_modulus),
224 c_uint8_ptr(p224_b),
225 c_uint8_ptr(p224_order),
226 c_size_t(len(p224_modulus)),
227 c_ulonglong(getrandbits(64))
228 )
229 if result:
230 raise ImportError("Error %d initializing P-224 context" % result)
231
232 context = SmartPointer(ec_p224_context.get(), _ec_lib.ec_free_context)
233 p224 = _Curve(Integer(p),
234 Integer(b),
235 Integer(order),
236 Integer(Gx),
237 Integer(Gy),
238 None,
239 224,
240 "1.3.132.0.33", # SEC 2
241 context,
242 "NIST P-224",
243 "ecdsa-sha2-nistp224",
244 "p224")
245 global p224_names
246 _curves.update(dict.fromkeys(p224_names, p224))
247
248
249 init_p224()
250 del init_p224
251
252
253 p256_names = ["p256", "NIST P-256", "P-256", "prime256v1", "secp256r1",
254 "nistp256"]
255
256
257 def init_p256():
258 p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff
259 b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
260 order = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551
261 Gx = 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296
262 Gy = 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5
263
264 p256_modulus = long_to_bytes(p, 32)
265 p256_b = long_to_bytes(b, 32)
266 p256_order = long_to_bytes(order, 32)
267
268 ec_p256_context = VoidPointer()
269 result = _ec_lib.ec_ws_new_context(ec_p256_context.address_of(),
270 c_uint8_ptr(p256_modulus),
271 c_uint8_ptr(p256_b),
272 c_uint8_ptr(p256_order),
273 c_size_t(len(p256_modulus)),
274 c_ulonglong(getrandbits(64))
275 )
276 if result:
277 raise ImportError("Error %d initializing P-256 context" % result)
278
279 context = SmartPointer(ec_p256_context.get(), _ec_lib.ec_free_context)
280 p256 = _Curve(Integer(p),
281 Integer(b),
282 Integer(order),
283 Integer(Gx),
284 Integer(Gy),
285 None,
286 256,
287 "1.2.840.10045.3.1.7", # ANSI X9.62 / SEC2
288 context,
289 "NIST P-256",
290 "ecdsa-sha2-nistp256",
291 "p256")
292 global p256_names
293 _curves.update(dict.fromkeys(p256_names, p256))
294
295
296 init_p256()
297 del init_p256
298
299
300 p384_names = ["p384", "NIST P-384", "P-384", "prime384v1", "secp384r1",
301 "nistp384"]
302
303
304 def init_p384():
305 p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff
306 b = 0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef
307 order = 0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973
308 Gx = 0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760aB7
309 Gy = 0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5F
310
311 p384_modulus = long_to_bytes(p, 48)
312 p384_b = long_to_bytes(b, 48)
313 p384_order = long_to_bytes(order, 48)
314
315 ec_p384_context = VoidPointer()
316 result = _ec_lib.ec_ws_new_context(ec_p384_context.address_of(),
317 c_uint8_ptr(p384_modulus),
318 c_uint8_ptr(p384_b),
319 c_uint8_ptr(p384_order),
320 c_size_t(len(p384_modulus)),
321 c_ulonglong(getrandbits(64))
322 )
323 if result:
324 raise ImportError("Error %d initializing P-384 context" % result)
325
326 context = SmartPointer(ec_p384_context.get(), _ec_lib.ec_free_context)
327 p384 = _Curve(Integer(p),
328 Integer(b),
329 Integer(order),
330 Integer(Gx),
331 Integer(Gy),
332 None,
333 384,
334 "1.3.132.0.34", # SEC 2
335 context,
336 "NIST P-384",
337 "ecdsa-sha2-nistp384",
338 "p384")
339 global p384_names
340 _curves.update(dict.fromkeys(p384_names, p384))
341
342
343 init_p384()
344 del init_p384
345
346
347 p521_names = ["p521", "NIST P-521", "P-521", "prime521v1", "secp521r1",
348 "nistp521"]
349
350
351 def init_p521():
352 p = 0x000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
353 b = 0x00000051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00
354 order = 0x000001fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409
355 Gx = 0x000000c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66
356 Gy = 0x0000011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650
357
358 p521_modulus = long_to_bytes(p, 66)
359 p521_b = long_to_bytes(b, 66)
360 p521_order = long_to_bytes(order, 66)
361
362 ec_p521_context = VoidPointer()
363 result = _ec_lib.ec_ws_new_context(ec_p521_context.address_of(),
364 c_uint8_ptr(p521_modulus),
365 c_uint8_ptr(p521_b),
366 c_uint8_ptr(p521_order),
367 c_size_t(len(p521_modulus)),
368 c_ulonglong(getrandbits(64))
369 )
370 if result:
371 raise ImportError("Error %d initializing P-521 context" % result)
372
373 context = SmartPointer(ec_p521_context.get(), _ec_lib.ec_free_context)
374 p521 = _Curve(Integer(p),
375 Integer(b),
376 Integer(order),
377 Integer(Gx),
378 Integer(Gy),
379 None,
380 521,
381 "1.3.132.0.35", # SEC 2
382 context,
383 "NIST P-521",
384 "ecdsa-sha2-nistp521",
385 "p521")
386 global p521_names
387 _curves.update(dict.fromkeys(p521_names, p521))
388
389
390 init_p521()
391 del init_p521
392
393
394 ed25519_names = ["ed25519", "Ed25519"]
395
396
397 def init_ed25519():
398 p = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed # 2**255 - 19
399 order = 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed
400 Gx = 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a
401 Gy = 0x6666666666666666666666666666666666666666666666666666666666666658
402
403 ed25519 = _Curve(Integer(p),
404 None,
405 Integer(order),
406 Integer(Gx),
407 Integer(Gy),
408 None,
409 255,
410 "1.3.101.112", # RFC8410
411 None,
412 "Ed25519", # Used throughout; do not change
413 "ssh-ed25519",
414 "ed25519")
415 global ed25519_names
416 _curves.update(dict.fromkeys(ed25519_names, ed25519))
417
418
419 init_ed25519()
420 del init_ed25519
421
422
423 ed448_names = ["ed448", "Ed448"]
424
425
426 def init_ed448():
427 p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffff # 2**448 - 2**224 - 1
428 order = 0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f3
429 Gx = 0x4f1970c66bed0ded221d15a622bf36da9e146570470f1767ea6de324a3d3a46412ae1af72ab66511433b80e18b00938e2626a82bc70cc05e
430 Gy = 0x693f46716eb6bc248876203756c9c7624bea73736ca3984087789c1e05a0c2d73ad3ff1ce67c39c4fdbd132c4ed7c8ad9808795bf230fa14
431
432 ed448_context = VoidPointer()
433 result = _ed448_lib.ed448_new_context(ed448_context.address_of())
434 if result:
435 raise ImportError("Error %d initializing Ed448 context" % result)
436
437 context = SmartPointer(ed448_context.get(), _ed448_lib.ed448_free_context)
438
439 ed448 = _Curve(Integer(p),
440 None,
441 Integer(order),
442 Integer(Gx),
443 Integer(Gy),
444 None,
445 448,
446 "1.3.101.113", # RFC8410
447 context,
448 "Ed448", # Used throughout; do not change
449 None,
450 "ed448")
451 global ed448_names
452 _curves.update(dict.fromkeys(ed448_names, ed448))
453
454
455 init_ed448()
456 del init_ed448
457
458
459 class UnsupportedEccFeature(ValueError):
460 pass
461
462
463 class EccPoint(object):
464 """A class to model a point on an Elliptic Curve.
465
466 The class supports operators for:
467
468 * Adding two points: ``R = S + T``
469 * In-place addition: ``S += T``
470 * Negating a point: ``R = -T``
471 * Comparing two points: ``if S == T: ...`` or ``if S != T: ...``
472 * Multiplying a point by a scalar: ``R = S*k``
473 * In-place multiplication by a scalar: ``T *= k``
474
475 :ivar x: The affine X-coordinate of the ECC point
476 :vartype x: integer
477
478 :ivar y: The affine Y-coordinate of the ECC point
479 :vartype y: integer
480
481 :ivar xy: The tuple with affine X- and Y- coordinates
482 """
483
484 def __init__(self, x, y, curve="p256"):
485
486 try:
487 self._curve = _curves[curve]
488 except KeyError:
489 raise ValueError("Unknown curve name %s" % str(curve))
490 self._curve_name = curve
491
492 modulus_bytes = self.size_in_bytes()
493
494 xb = long_to_bytes(x, modulus_bytes)
495 yb = long_to_bytes(y, modulus_bytes)
496 if len(xb) != modulus_bytes or len(yb) != modulus_bytes:
497 raise ValueError("Incorrect coordinate length")
498
499 new_point = lib_func(self, "new_point")
500 free_func = lib_func(self, "free_point")
501
502 self._point = VoidPointer()
503 try:
504 context = self._curve.context.get()
505 except AttributeError:
506 context = null_pointer
507 result = new_point(self._point.address_of(),
508 c_uint8_ptr(xb),
509 c_uint8_ptr(yb),
510 c_size_t(modulus_bytes),
511 context)
512
513 if result:
514 if result == 15:
515 raise ValueError("The EC point does not belong to the curve")
516 raise ValueError("Error %d while instantiating an EC point" % result)
517
518 # Ensure that object disposal of this Python object will (eventually)
519 # free the memory allocated by the raw library for the EC point
520 self._point = SmartPointer(self._point.get(), free_func)
521
522 def set(self, point):
523 clone = lib_func(self, "clone")
524 free_func = lib_func(self, "free_point")
525
526 self._point = VoidPointer()
527 result = clone(self._point.address_of(),
528 point._point.get())
529
530 if result:
531 raise ValueError("Error %d while cloning an EC point" % result)
532
533 self._point = SmartPointer(self._point.get(), free_func)
534 return self
535
536 def __eq__(self, point):
537 if not isinstance(point, EccPoint):
538 return False
539
540 cmp_func = lib_func(self, "cmp")
541 return 0 == cmp_func(self._point.get(), point._point.get())
542
543 # Only needed for Python 2
544 def __ne__(self, point):
545 return not self == point
546
547 def __neg__(self):
548 neg_func = lib_func(self, "neg")
549 np = self.copy()
550 result = neg_func(np._point.get())
551 if result:
552 raise ValueError("Error %d while inverting an EC point" % result)
553 return np
554
555 def copy(self):
556 """Return a copy of this point."""
557 x, y = self.xy
558 np = EccPoint(x, y, self._curve_name)
559 return np
560
561 def _is_eddsa(self):
562 return self._curve.name in ("ed25519", "ed448")
563
564 def is_point_at_infinity(self):
565 """``True`` if this is the *point-at-infinity*."""
566
567 if self._is_eddsa():
568 return self.x == 0
569 else:
570 return self.xy == (0, 0)
571
572 def point_at_infinity(self):
573 """Return the *point-at-infinity* for the curve."""
574
575 if self._is_eddsa():
576 return EccPoint(0, 1, self._curve_name)
577 else:
578 return EccPoint(0, 0, self._curve_name)
579
580 @property
581 def x(self):
582 return self.xy[0]
583
584 @property
585 def y(self):
586 return self.xy[1]
587
588 @property
589 def xy(self):
590 modulus_bytes = self.size_in_bytes()
591 xb = bytearray(modulus_bytes)
592 yb = bytearray(modulus_bytes)
593 get_xy = lib_func(self, "get_xy")
594 result = get_xy(c_uint8_ptr(xb),
595 c_uint8_ptr(yb),
596 c_size_t(modulus_bytes),
597 self._point.get())
598 if result:
599 raise ValueError("Error %d while encoding an EC point" % result)
600
601 return (Integer(bytes_to_long(xb)), Integer(bytes_to_long(yb)))
602
603 def size_in_bytes(self):
604 """Size of each coordinate, in bytes."""
605 return (self.size_in_bits() + 7) // 8
606
607 def size_in_bits(self):
608 """Size of each coordinate, in bits."""
609 return self._curve.modulus_bits
610
611 def double(self):
612 """Double this point (in-place operation).
613
614 Returns:
615 This same object (to enable chaining).
616 """
617
618 double_func = lib_func(self, "double")
619 result = double_func(self._point.get())
620 if result:
621 raise ValueError("Error %d while doubling an EC point" % result)
622 return self
623
624 def __iadd__(self, point):
625 """Add a second point to this one"""
626
627 add_func = lib_func(self, "add")
628 result = add_func(self._point.get(), point._point.get())
629 if result:
630 if result == 16:
631 raise ValueError("EC points are not on the same curve")
632 raise ValueError("Error %d while adding two EC points" % result)
633 return self
634
635 def __add__(self, point):
636 """Return a new point, the addition of this one and another"""
637
638 np = self.copy()
639 np += point
640 return np
641
642 def __imul__(self, scalar):
643 """Multiply this point by a scalar"""
644
645 scalar_func = lib_func(self, "scalar")
646 if scalar < 0:
647 raise ValueError("Scalar multiplication is only defined for non-negative integers")
648 sb = long_to_bytes(scalar)
649 result = scalar_func(self._point.get(),
650 c_uint8_ptr(sb),
651 c_size_t(len(sb)),
652 c_ulonglong(getrandbits(64)))
653 if result:
654 raise ValueError("Error %d during scalar multiplication" % result)
655 return self
656
657 def __mul__(self, scalar):
658 """Return a new point, the scalar product of this one"""
659
660 np = self.copy()
661 np *= scalar
662 return np
663
664 def __rmul__(self, left_hand):
665 return self.__mul__(left_hand)
666
667
668 # Last piece of initialization
669 p192_G = EccPoint(_curves['p192'].Gx, _curves['p192'].Gy, "p192")
670 p192 = _curves['p192']._replace(G=p192_G)
671 _curves.update(dict.fromkeys(p192_names, p192))
672 del p192_G, p192, p192_names
673
674 p224_G = EccPoint(_curves['p224'].Gx, _curves['p224'].Gy, "p224")
675 p224 = _curves['p224']._replace(G=p224_G)
676 _curves.update(dict.fromkeys(p224_names, p224))
677 del p224_G, p224, p224_names
678
679 p256_G = EccPoint(_curves['p256'].Gx, _curves['p256'].Gy, "p256")
680 p256 = _curves['p256']._replace(G=p256_G)
681 _curves.update(dict.fromkeys(p256_names, p256))
682 del p256_G, p256, p256_names
683
684 p384_G = EccPoint(_curves['p384'].Gx, _curves['p384'].Gy, "p384")
685 p384 = _curves['p384']._replace(G=p384_G)
686 _curves.update(dict.fromkeys(p384_names, p384))
687 del p384_G, p384, p384_names
688
689 p521_G = EccPoint(_curves['p521'].Gx, _curves['p521'].Gy, "p521")
690 p521 = _curves['p521']._replace(G=p521_G)
691 _curves.update(dict.fromkeys(p521_names, p521))
692 del p521_G, p521, p521_names
693
694 ed25519_G = EccPoint(_curves['Ed25519'].Gx, _curves['Ed25519'].Gy, "Ed25519")
695 ed25519 = _curves['Ed25519']._replace(G=ed25519_G)
696 _curves.update(dict.fromkeys(ed25519_names, ed25519))
697 del ed25519_G, ed25519, ed25519_names
698
699 ed448_G = EccPoint(_curves['Ed448'].Gx, _curves['Ed448'].Gy, "Ed448")
700 ed448 = _curves['Ed448']._replace(G=ed448_G)
701 _curves.update(dict.fromkeys(ed448_names, ed448))
702 del ed448_G, ed448, ed448_names
703
704
705 class EccKey(object):
706 r"""Class defining an ECC key.
707 Do not instantiate directly.
708 Use :func:`generate`, :func:`construct` or :func:`import_key` instead.
709
710 :ivar curve: The name of the curve as defined in the `ECC table`_.
711 :vartype curve: string
712
713 :ivar pointQ: an ECC point representating the public component.
714 :vartype pointQ: :class:`EccPoint`
715
716 :ivar d: A scalar that represents the private component
717 in NIST P curves. It is smaller than the
718 order of the generator point.
719 :vartype d: integer
720
721 :ivar seed: A seed that representats the private component
722 in EdDSA curves
723 (Ed25519, 32 bytes; Ed448, 57 bytes).
724 :vartype seed: bytes
725 """
726
727 def __init__(self, **kwargs):
728 """Create a new ECC key
729
730 Keywords:
731 curve : string
732 The name of the curve.
733 d : integer
734 Mandatory for a private key one NIST P curves.
735 It must be in the range ``[1..order-1]``.
736 seed : bytes
737 Mandatory for a private key on the Ed25519 (32 bytes)
738 or Ed448 (57 bytes) curve.
739 point : EccPoint
740 Mandatory for a public key. If provided for a private key,
741 the implementation will NOT check whether it matches ``d``.
742
743 Only one parameter among ``d``, ``seed`` or ``point`` may be used.
744 """
745
746 kwargs_ = dict(kwargs)
747 curve_name = kwargs_.pop("curve", None)
748 self._d = kwargs_.pop("d", None)
749 self._seed = kwargs_.pop("seed", None)
750 self._point = kwargs_.pop("point", None)
751 if curve_name is None and self._point:
752 curve_name = self._point._curve_name
753 if kwargs_:
754 raise TypeError("Unknown parameters: " + str(kwargs_))
755
756 if curve_name not in _curves:
757 raise ValueError("Unsupported curve (%s)" % curve_name)
758 self._curve = _curves[curve_name]
759 self.curve = self._curve.desc
760
761 count = int(self._d is not None) + int(self._seed is not None)
762
763 if count == 0:
764 if self._point is None:
765 raise ValueError("At lest one between parameters 'point', 'd' or 'seed' must be specified")
766 return
767
768 if count == 2:
769 raise ValueError("Parameters d and seed are mutually exclusive")
770
771 # NIST P curves work with d, EdDSA works with seed
772
773 if not self._is_eddsa():
774 if self._seed is not None:
775 raise ValueError("Parameter 'seed' can only be used with Ed25519 or Ed448")
776 self._d = Integer(self._d)
777 if not 1 <= self._d < self._curve.order:
778 raise ValueError("Parameter d must be an integer smaller than the curve order")
779 else:
780 if self._d is not None:
781 raise ValueError("Parameter d can only be used with NIST P curves")
782 # RFC 8032, 5.1.5
783 if self._curve.name == "ed25519":
784 if len(self._seed) != 32:
785 raise ValueError("Parameter seed must be 32 bytes long for Ed25519")
786 seed_hash = SHA512.new(self._seed).digest() # h
787 self._prefix = seed_hash[32:]
788 tmp = bytearray(seed_hash[:32])
789 tmp[0] &= 0xF8
790 tmp[31] = (tmp[31] & 0x7F) | 0x40
791 # RFC 8032, 5.2.5
792 elif self._curve.name == "ed448":
793 if len(self._seed) != 57:
794 raise ValueError("Parameter seed must be 57 bytes long for Ed448")
795 seed_hash = SHAKE256.new(self._seed).read(114) # h
796 self._prefix = seed_hash[57:]
797 tmp = bytearray(seed_hash[:57])
798 tmp[0] &= 0xFC
799 tmp[55] |= 0x80
800 tmp[56] = 0
801 self._d = Integer.from_bytes(tmp, byteorder='little')
802
803 def _is_eddsa(self):
804 return self._curve.desc in ("Ed25519", "Ed448")
805
806 def __eq__(self, other):
807 if not isinstance(other, EccKey):
808 return False
809
810 if other.has_private() != self.has_private():
811 return False
812
813 return other.pointQ == self.pointQ
814
815 def __repr__(self):
816 if self.has_private():
817 if self._is_eddsa():
818 extra = ", seed=%s" % tostr(binascii.hexlify(self._seed))
819 else:
820 extra = ", d=%d" % int(self._d)
821 else:
822 extra = ""
823 x, y = self.pointQ.xy
824 return "EccKey(curve='%s', point_x=%d, point_y=%d%s)" % (self._curve.desc, x, y, extra)
825
826 def has_private(self):
827 """``True`` if this key can be used for making signatures or decrypting data."""
828
829 return self._d is not None
830
831 # ECDSA
832 def _sign(self, z, k):
833 assert 0 < k < self._curve.order
834
835 order = self._curve.order
836 blind = Integer.random_range(min_inclusive=1,
837 max_exclusive=order)
838
839 blind_d = self._d * blind
840 inv_blind_k = (blind * k).inverse(order)
841
842 r = (self._curve.G * k).x % order
843 s = inv_blind_k * (blind * z + blind_d * r) % order
844 return (r, s)
845
846 # ECDSA
847 def _verify(self, z, rs):
848 order = self._curve.order
849 sinv = rs[1].inverse(order)
850 point1 = self._curve.G * ((sinv * z) % order)
851 point2 = self.pointQ * ((sinv * rs[0]) % order)
852 return (point1 + point2).x == rs[0]
853
854 @property
855 def d(self):
856 if not self.has_private():
857 raise ValueError("This is not a private ECC key")
858 return self._d
859
860 @property
861 def seed(self):
862 if not self.has_private():
863 raise ValueError("This is not a private ECC key")
864 return self._seed
865
866 @property
867 def pointQ(self):
868 if self._point is None:
869 self._point = self._curve.G * self._d
870 return self._point
871
872 def public_key(self):
873 """A matching ECC public key.
874
875 Returns:
876 a new :class:`EccKey` object
877 """
878
879 return EccKey(curve=self._curve.desc, point=self.pointQ)
880
881 def _export_SEC1(self, compress):
882 if self._is_eddsa():
883 raise ValueError("SEC1 format is unsupported for EdDSA curves")
884
885 # See 2.2 in RFC5480 and 2.3.3 in SEC1
886 #
887 # The first byte is:
888 # - 0x02: compressed, only X-coordinate, Y-coordinate is even
889 # - 0x03: compressed, only X-coordinate, Y-coordinate is odd
890 # - 0x04: uncompressed, X-coordinate is followed by Y-coordinate
891 #
892 # PAI is in theory encoded as 0x00.
893
894 modulus_bytes = self.pointQ.size_in_bytes()
895
896 if compress:
897 if self.pointQ.y.is_odd():
898 first_byte = b'\x03'
899 else:
900 first_byte = b'\x02'
901 public_key = (first_byte +
902 self.pointQ.x.to_bytes(modulus_bytes))
903 else:
904 public_key = (b'\x04' +
905 self.pointQ.x.to_bytes(modulus_bytes) +
906 self.pointQ.y.to_bytes(modulus_bytes))
907 return public_key
908
909 def _export_eddsa(self):
910 x, y = self.pointQ.xy
911 if self._curve.name == "ed25519":
912 result = bytearray(y.to_bytes(32, byteorder='little'))
913 result[31] = ((x & 1) << 7) | result[31]
914 elif self._curve.name == "ed448":
915 result = bytearray(y.to_bytes(57, byteorder='little'))
916 result[56] = (x & 1) << 7
917 else:
918 raise ValueError("Not an EdDSA key to export")
919 return bytes(result)
920
921 def _export_subjectPublicKeyInfo(self, compress):
922 if self._is_eddsa():
923 oid = self._curve.oid
924 public_key = self._export_eddsa()
925 params = None
926 else:
927 oid = "1.2.840.10045.2.1" # unrestricted
928 public_key = self._export_SEC1(compress)
929 params = DerObjectId(self._curve.oid)
930
931 return _create_subject_public_key_info(oid,
932 public_key,
933 params)
934
935 def _export_rfc5915_private_der(self, include_ec_params=True):
936
937 assert self.has_private()
938
939 # ECPrivateKey ::= SEQUENCE {
940 # version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
941 # privateKey OCTET STRING,
942 # parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
943 # publicKey [1] BIT STRING OPTIONAL
944 # }
945
946 # Public key - uncompressed form
947 modulus_bytes = self.pointQ.size_in_bytes()
948 public_key = (b'\x04' +
949 self.pointQ.x.to_bytes(modulus_bytes) +
950 self.pointQ.y.to_bytes(modulus_bytes))
951
952 seq = [1,
953 DerOctetString(self.d.to_bytes(modulus_bytes)),
954 DerObjectId(self._curve.oid, explicit=0),
955 DerBitString(public_key, explicit=1)]
956
957 if not include_ec_params:
958 del seq[2]
959
960 return DerSequence(seq).encode()
961
962 def _export_pkcs8(self, **kwargs):
963 from Crypto.IO import PKCS8
964
965 if kwargs.get('passphrase', None) is not None and 'protection' not in kwargs:
966 raise ValueError("At least the 'protection' parameter must be present")
967
968 if self._is_eddsa():
969 oid = self._curve.oid
970 private_key = DerOctetString(self._seed).encode()
971 params = None
972 else:
973 oid = "1.2.840.10045.2.1" # unrestricted
974 private_key = self._export_rfc5915_private_der(include_ec_params=False)
975 params = DerObjectId(self._curve.oid)
976
977 result = PKCS8.wrap(private_key,
978 oid,
979 key_params=params,
980 **kwargs)
981 return result
982
983 def _export_public_pem(self, compress):
984 from Crypto.IO import PEM
985
986 encoded_der = self._export_subjectPublicKeyInfo(compress)
987 return PEM.encode(encoded_der, "PUBLIC KEY")
988
989 def _export_private_pem(self, passphrase, **kwargs):
990 from Crypto.IO import PEM
991
992 encoded_der = self._export_rfc5915_private_der()
993 return PEM.encode(encoded_der, "EC PRIVATE KEY", passphrase, **kwargs)
994
995 def _export_private_clear_pkcs8_in_clear_pem(self):
996 from Crypto.IO import PEM
997
998 encoded_der = self._export_pkcs8()
999 return PEM.encode(encoded_der, "PRIVATE KEY")
1000
1001 def _export_private_encrypted_pkcs8_in_clear_pem(self, passphrase, **kwargs):
1002 from Crypto.IO import PEM
1003
1004 assert passphrase
1005 if 'protection' not in kwargs:
1006 raise ValueError("At least the 'protection' parameter should be present")
1007 encoded_der = self._export_pkcs8(passphrase=passphrase, **kwargs)
1008 return PEM.encode(encoded_der, "ENCRYPTED PRIVATE KEY")
1009
1010 def _export_openssh(self, compress):
1011 if self.has_private():
1012 raise ValueError("Cannot export OpenSSH private keys")
1013
1014 desc = self._curve.openssh
1015
1016 if desc is None:
1017 raise ValueError("Cannot export %s keys as OpenSSH" % self._curve.name)
1018 elif desc == "ssh-ed25519":
1019 public_key = self._export_eddsa()
1020 comps = (tobytes(desc), tobytes(public_key))
1021 else:
1022 modulus_bytes = self.pointQ.size_in_bytes()
1023
1024 if compress:
1025 first_byte = 2 + self.pointQ.y.is_odd()
1026 public_key = (bchr(first_byte) +
1027 self.pointQ.x.to_bytes(modulus_bytes))
1028 else:
1029 public_key = (b'\x04' +
1030 self.pointQ.x.to_bytes(modulus_bytes) +
1031 self.pointQ.y.to_bytes(modulus_bytes))
1032
1033 middle = desc.split("-")[2]
1034 comps = (tobytes(desc), tobytes(middle), public_key)
1035
1036 blob = b"".join([struct.pack(">I", len(x)) + x for x in comps])
1037 return desc + " " + tostr(binascii.b2a_base64(blob))
1038
1039 def export_key(self, **kwargs):
1040 """Export this ECC key.
1041
1042 Args:
1043 format (string):
1044 The output format:
1045
1046 - ``'DER'``. The key will be encoded in ASN.1 DER format (binary).
1047 For a public key, the ASN.1 ``subjectPublicKeyInfo`` structure
1048 defined in `RFC5480`_ will be used.
1049 For a private key, the ASN.1 ``ECPrivateKey`` structure defined
1050 in `RFC5915`_ is used instead (possibly within a PKCS#8 envelope,
1051 see the ``use_pkcs8`` flag below).
1052 - ``'PEM'``. The key will be encoded in a PEM_ envelope (ASCII).
1053 - ``'OpenSSH'``. The key will be encoded in the OpenSSH_ format
1054 (ASCII, public keys only).
1055 - ``'SEC1'``. The public key (i.e., the EC point) will be encoded
1056 into ``bytes`` according to Section 2.3.3 of `SEC1`_
1057 (which is a subset of the older X9.62 ITU standard).
1058 Only for NIST P-curves.
1059 - ``'raw'``. The public key will be encoded as ``bytes``,
1060 without any metadata.
1061
1062 * For NIST P-curves: equivalent to ``'SEC1'``.
1063 * For EdDSA curves: ``bytes`` in the format defined in `RFC8032`_.
1064
1065 passphrase (bytes or string):
1066 (*Private keys only*) The passphrase to protect the
1067 private key.
1068
1069 use_pkcs8 (boolean):
1070 (*Private keys only*)
1071 If ``True`` (default and recommended), the `PKCS#8`_ representation
1072 will be used. It must be ``True`` for EdDSA curves.
1073
1074 If ``False`` and a passphrase is present, the obsolete PEM
1075 encryption will be used.
1076
1077 protection (string):
1078 When a private key is exported with password-protection
1079 and PKCS#8 (both ``DER`` and ``PEM`` formats), this parameter MUST be
1080 present,
1081 For all possible protection schemes,
1082 refer to :ref:`the encryption parameters of PKCS#8<enc_params>`.
1083 It is recommended to use ``'PBKDF2WithHMAC-SHA5126AndAES128-CBC'``.
1084
1085 compress (boolean):
1086 If ``True``, the method returns a more compact representation
1087 of the public key, with the X-coordinate only.
1088
1089 If ``False`` (default), the method returns the full public key.
1090
1091 This parameter is ignored for EdDSA curves, as compression is
1092 mandatory.
1093
1094 prot_params (dict):
1095 When a private key is exported with password-protection
1096 and PKCS#8 (both ``DER`` and ``PEM`` formats), this dictionary
1097 contains the parameters to use to derive the encryption key
1098 from the passphrase.
1099 For all possible values,
1100 refer to :ref:`the encryption parameters of PKCS#8<enc_params>`.
1101 The recommendation is to use ``{'iteration_count':21000}`` for PBKDF2,
1102 and ``{'iteration_count':131072}`` for scrypt.
1103
1104 .. warning::
1105 If you don't provide a passphrase, the private key will be
1106 exported in the clear!
1107
1108 .. note::
1109 When exporting a private key with password-protection and `PKCS#8`_
1110 (both ``DER`` and ``PEM`` formats), any extra parameters
1111 to ``export_key()`` will be passed to :mod:`Crypto.IO.PKCS8`.
1112
1113 .. _PEM: http://www.ietf.org/rfc/rfc1421.txt
1114 .. _`PEM encryption`: http://www.ietf.org/rfc/rfc1423.txt
1115 .. _OpenSSH: http://www.openssh.com/txt/rfc5656.txt
1116 .. _RFC5480: https://tools.ietf.org/html/rfc5480
1117 .. _SEC1: https://www.secg.org/sec1-v2.pdf
1118
1119 Returns:
1120 A multi-line string (for ``'PEM'`` and ``'OpenSSH'``) or
1121 ``bytes`` (for ``'DER'``, ``'SEC1'``, and ``'raw'``) with the encoded key.
1122 """
1123
1124 args = kwargs.copy()
1125 ext_format = args.pop("format")
1126 if ext_format not in ("PEM", "DER", "OpenSSH", "SEC1", "raw"):
1127 raise ValueError("Unknown format '%s'" % ext_format)
1128
1129 compress = args.pop("compress", False)
1130
1131 if self.has_private():
1132 passphrase = args.pop("passphrase", None)
1133 if is_string(passphrase):
1134 passphrase = tobytes(passphrase)
1135 if not passphrase:
1136 raise ValueError("Empty passphrase")
1137 use_pkcs8 = args.pop("use_pkcs8", True)
1138
1139 if not use_pkcs8:
1140 if self._is_eddsa():
1141 raise ValueError("'pkcs8' must be True for EdDSA curves")
1142 if 'protection' in args:
1143 raise ValueError("'protection' is only supported for PKCS#8")
1144
1145 if ext_format == "PEM":
1146 if use_pkcs8:
1147 if passphrase:
1148 return self._export_private_encrypted_pkcs8_in_clear_pem(passphrase, **args)
1149 else:
1150 return self._export_private_clear_pkcs8_in_clear_pem()
1151 else:
1152 return self._export_private_pem(passphrase, **args)
1153 elif ext_format == "DER":
1154 # DER
1155 if passphrase and not use_pkcs8:
1156 raise ValueError("Private keys can only be encrpyted with DER using PKCS#8")
1157 if use_pkcs8:
1158 return self._export_pkcs8(passphrase=passphrase, **args)
1159 else:
1160 return self._export_rfc5915_private_der()
1161 else:
1162 raise ValueError("Private keys cannot be exported "
1163 "in the '%s' format" % ext_format)
1164 else: # Public key
1165 if args:
1166 raise ValueError("Unexpected parameters: '%s'" % args)
1167 if ext_format == "PEM":
1168 return self._export_public_pem(compress)
1169 elif ext_format == "DER":
1170 return self._export_subjectPublicKeyInfo(compress)
1171 elif ext_format == "SEC1":
1172 return self._export_SEC1(compress)
1173 elif ext_format == "raw":
1174 if self._curve.name in ('ed25519', 'ed448'):
1175 return self._export_eddsa()
1176 else:
1177 return self._export_SEC1(compress)
1178 else:
1179 return self._export_openssh(compress)
1180
1181
1182 def generate(**kwargs):
1183 """Generate a new private key on the given curve.
1184
1185 Args:
1186
1187 curve (string):
1188 Mandatory. It must be a curve name defined in the `ECC table`_.
1189
1190 randfunc (callable):
1191 Optional. The RNG to read randomness from.
1192 If ``None``, :func:`Crypto.Random.get_random_bytes` is used.
1193 """
1194
1195 curve_name = kwargs.pop("curve")
1196 curve = _curves[curve_name]
1197 randfunc = kwargs.pop("randfunc", get_random_bytes)
1198 if kwargs:
1199 raise TypeError("Unknown parameters: " + str(kwargs))
1200
1201 if _curves[curve_name].name == "ed25519":
1202 seed = randfunc(32)
1203 new_key = EccKey(curve=curve_name, seed=seed)
1204 elif _curves[curve_name].name == "ed448":
1205 seed = randfunc(57)
1206 new_key = EccKey(curve=curve_name, seed=seed)
1207 else:
1208 d = Integer.random_range(min_inclusive=1,
1209 max_exclusive=curve.order,
1210 randfunc=randfunc)
1211 new_key = EccKey(curve=curve_name, d=d)
1212
1213 return new_key
1214
1215
1216 def construct(**kwargs):
1217 """Build a new ECC key (private or public) starting
1218 from some base components.
1219
1220 In most cases, you will already have an existing key
1221 which you can read in with :func:`import_key` instead
1222 of this function.
1223
1224 Args:
1225 curve (string):
1226 Mandatory. The name of the elliptic curve, as defined in the `ECC table`_.
1227
1228 d (integer):
1229 Mandatory for a private key and a NIST P-curve (e.g., P-256):
1230 the integer in the range ``[1..order-1]`` that represents the key.
1231
1232 seed (bytes):
1233 Mandatory for a private key and an EdDSA curve.
1234 It must be 32 bytes for Ed25519, and 57 bytes for Ed448.
1235
1236 point_x (integer):
1237 Mandatory for a public key: the X coordinate (affine) of the ECC point.
1238
1239 point_y (integer):
1240 Mandatory for a public key: the Y coordinate (affine) of the ECC point.
1241
1242 Returns:
1243 :class:`EccKey` : a new ECC key object
1244 """
1245
1246 curve_name = kwargs["curve"]
1247 curve = _curves[curve_name]
1248 point_x = kwargs.pop("point_x", None)
1249 point_y = kwargs.pop("point_y", None)
1250
1251 if "point" in kwargs:
1252 raise TypeError("Unknown keyword: point")
1253
1254 if None not in (point_x, point_y):
1255 # ValueError is raised if the point is not on the curve
1256 kwargs["point"] = EccPoint(point_x, point_y, curve_name)
1257
1258 new_key = EccKey(**kwargs)
1259
1260 # Validate that the private key matches the public one
1261 # because EccKey will not do that automatically
1262 if new_key.has_private() and 'point' in kwargs:
1263 pub_key = curve.G * new_key.d
1264 if pub_key.xy != (point_x, point_y):
1265 raise ValueError("Private and public ECC keys do not match")
1266
1267 return new_key
1268
1269
1270 def _import_public_der(ec_point, curve_oid=None, curve_name=None):
1271 """Convert an encoded EC point into an EccKey object
1272
1273 ec_point: byte string with the EC point (SEC1-encoded)
1274 curve_oid: string with the name the curve
1275 curve_name: string with the OID of the curve
1276
1277 Either curve_id or curve_name must be specified
1278
1279 """
1280
1281 for _curve_name, curve in _curves.items():
1282 if curve_oid and curve.oid == curve_oid:
1283 break
1284 if curve_name == _curve_name:
1285 break
1286 else:
1287 if curve_oid:
1288 raise UnsupportedEccFeature("Unsupported ECC curve (OID: %s)" % curve_oid)
1289 else:
1290 raise UnsupportedEccFeature("Unsupported ECC curve (%s)" % curve_name)
1291
1292 # See 2.2 in RFC5480 and 2.3.3 in SEC1
1293 # The first byte is:
1294 # - 0x02: compressed, only X-coordinate, Y-coordinate is even
1295 # - 0x03: compressed, only X-coordinate, Y-coordinate is odd
1296 # - 0x04: uncompressed, X-coordinate is followed by Y-coordinate
1297 #
1298 # PAI is in theory encoded as 0x00.
1299
1300 modulus_bytes = curve.p.size_in_bytes()
1301 point_type = bord(ec_point[0])
1302
1303 # Uncompressed point
1304 if point_type == 0x04:
1305 if len(ec_point) != (1 + 2 * modulus_bytes):
1306 raise ValueError("Incorrect EC point length")
1307 x = Integer.from_bytes(ec_point[1:modulus_bytes+1])
1308 y = Integer.from_bytes(ec_point[modulus_bytes+1:])
1309 # Compressed point
1310 elif point_type in (0x02, 0x03):
1311 if len(ec_point) != (1 + modulus_bytes):
1312 raise ValueError("Incorrect EC point length")
1313 x = Integer.from_bytes(ec_point[1:])
1314 # Right now, we only support Short Weierstrass curves
1315 y = (x**3 - x*3 + curve.b).sqrt(curve.p)
1316 if point_type == 0x02 and y.is_odd():
1317 y = curve.p - y
1318 if point_type == 0x03 and y.is_even():
1319 y = curve.p - y
1320 else:
1321 raise ValueError("Incorrect EC point encoding")
1322
1323 return construct(curve=_curve_name, point_x=x, point_y=y)
1324
1325
1326 def _import_subjectPublicKeyInfo(encoded, *kwargs):
1327 """Convert a subjectPublicKeyInfo into an EccKey object"""
1328
1329 # See RFC5480
1330
1331 # Parse the generic subjectPublicKeyInfo structure
1332 oid, ec_point, params = _expand_subject_public_key_info(encoded)
1333
1334 nist_p_oids = (
1335 "1.2.840.10045.2.1", # id-ecPublicKey (unrestricted)
1336 "1.3.132.1.12", # id-ecDH
1337 "1.3.132.1.13" # id-ecMQV
1338 )
1339 eddsa_oids = {
1340 "1.3.101.112": ("Ed25519", _import_ed25519_public_key), # id-Ed25519
1341 "1.3.101.113": ("Ed448", _import_ed448_public_key) # id-Ed448
1342 }
1343
1344 if oid in nist_p_oids:
1345 # See RFC5480
1346
1347 # Parameters are mandatory and encoded as ECParameters
1348 # ECParameters ::= CHOICE {
1349 # namedCurve OBJECT IDENTIFIER
1350 # -- implicitCurve NULL
1351 # -- specifiedCurve SpecifiedECDomain
1352 # }
1353 # implicitCurve and specifiedCurve are not supported (as per RFC)
1354 if not params:
1355 raise ValueError("Missing ECC parameters for ECC OID %s" % oid)
1356 try:
1357 curve_oid = DerObjectId().decode(params).value
1358 except ValueError:
1359 raise ValueError("Error decoding namedCurve")
1360
1361 # ECPoint ::= OCTET STRING
1362 return _import_public_der(ec_point, curve_oid=curve_oid)
1363
1364 elif oid in eddsa_oids:
1365 # See RFC8410
1366 curve_name, import_eddsa_public_key = eddsa_oids[oid]
1367
1368 # Parameters must be absent
1369 if params:
1370 raise ValueError("Unexpected ECC parameters for ECC OID %s" % oid)
1371
1372 x, y = import_eddsa_public_key(ec_point)
1373 return construct(point_x=x, point_y=y, curve=curve_name)
1374 else:
1375 raise UnsupportedEccFeature("Unsupported ECC OID: %s" % oid)
1376
1377
1378 def _import_rfc5915_der(encoded, passphrase, curve_oid=None):
1379
1380 # See RFC5915 https://tools.ietf.org/html/rfc5915
1381 #
1382 # ECPrivateKey ::= SEQUENCE {
1383 # version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
1384 # privateKey OCTET STRING,
1385 # parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
1386 # publicKey [1] BIT STRING OPTIONAL
1387 # }
1388
1389 private_key = DerSequence().decode(encoded, nr_elements=(3, 4))
1390 if private_key[0] != 1:
1391 raise ValueError("Incorrect ECC private key version")
1392
1393 try:
1394 parameters = DerObjectId(explicit=0).decode(private_key[2]).value
1395 if curve_oid is not None and parameters != curve_oid:
1396 raise ValueError("Curve mismatch")
1397 curve_oid = parameters
1398 except ValueError:
1399 pass
1400
1401 if curve_oid is None:
1402 raise ValueError("No curve found")
1403
1404 for curve_name, curve in _curves.items():
1405 if curve.oid == curve_oid:
1406 break
1407 else:
1408 raise UnsupportedEccFeature("Unsupported ECC curve (OID: %s)" % curve_oid)
1409
1410 scalar_bytes = DerOctetString().decode(private_key[1]).payload
1411 modulus_bytes = curve.p.size_in_bytes()
1412 if len(scalar_bytes) != modulus_bytes:
1413 raise ValueError("Private key is too small")
1414 d = Integer.from_bytes(scalar_bytes)
1415
1416 # Decode public key (if any)
1417 if len(private_key) > 2:
1418 public_key_enc = DerBitString(explicit=1).decode(private_key[-1]).value
1419 public_key = _import_public_der(public_key_enc, curve_oid=curve_oid)
1420 point_x = public_key.pointQ.x
1421 point_y = public_key.pointQ.y
1422 else:
1423 point_x = point_y = None
1424
1425 return construct(curve=curve_name, d=d, point_x=point_x, point_y=point_y)
1426
1427
1428 def _import_pkcs8(encoded, passphrase):
1429 from Crypto.IO import PKCS8
1430
1431 algo_oid, private_key, params = PKCS8.unwrap(encoded, passphrase)
1432
1433 nist_p_oids = (
1434 "1.2.840.10045.2.1", # id-ecPublicKey (unrestricted)
1435 "1.3.132.1.12", # id-ecDH
1436 "1.3.132.1.13" # id-ecMQV
1437 )
1438 eddsa_oids = {
1439 "1.3.101.112": "Ed25519", # id-Ed25519
1440 "1.3.101.113": "Ed448", # id-Ed448
1441 }
1442
1443 if algo_oid in nist_p_oids:
1444 curve_oid = DerObjectId().decode(params).value
1445 return _import_rfc5915_der(private_key, passphrase, curve_oid)
1446 elif algo_oid in eddsa_oids:
1447 if params is not None:
1448 raise ValueError("EdDSA ECC private key must not have parameters")
1449 curve_oid = None
1450 seed = DerOctetString().decode(private_key).payload
1451 return construct(curve=eddsa_oids[algo_oid], seed=seed)
1452 else:
1453 raise UnsupportedEccFeature("Unsupported ECC purpose (OID: %s)" % algo_oid)
1454
1455
1456 def _import_x509_cert(encoded, *kwargs):
1457
1458 sp_info = _extract_subject_public_key_info(encoded)
1459 return _import_subjectPublicKeyInfo(sp_info)
1460
1461
1462 def _import_der(encoded, passphrase):
1463
1464 try:
1465 return _import_subjectPublicKeyInfo(encoded, passphrase)
1466 except UnsupportedEccFeature as err:
1467 raise err
1468 except (ValueError, TypeError, IndexError):
1469 pass
1470
1471 try:
1472 return _import_x509_cert(encoded, passphrase)
1473 except UnsupportedEccFeature as err:
1474 raise err
1475 except (ValueError, TypeError, IndexError):
1476 pass
1477
1478 try:
1479 return _import_rfc5915_der(encoded, passphrase)
1480 except UnsupportedEccFeature as err:
1481 raise err
1482 except (ValueError, TypeError, IndexError):
1483 pass
1484
1485 try:
1486 return _import_pkcs8(encoded, passphrase)
1487 except UnsupportedEccFeature as err:
1488 raise err
1489 except (ValueError, TypeError, IndexError):
1490 pass
1491
1492 raise ValueError("Not an ECC DER key")
1493
1494
1495 def _import_openssh_public(encoded):
1496 parts = encoded.split(b' ')
1497 if len(parts) not in (2, 3):
1498 raise ValueError("Not an openssh public key")
1499
1500 try:
1501 keystring = binascii.a2b_base64(parts[1])
1502
1503 keyparts = []
1504 while len(keystring) > 4:
1505 lk = struct.unpack(">I", keystring[:4])[0]
1506 keyparts.append(keystring[4:4 + lk])
1507 keystring = keystring[4 + lk:]
1508
1509 if parts[0] != keyparts[0]:
1510 raise ValueError("Mismatch in openssh public key")
1511
1512 # NIST P curves
1513 if parts[0].startswith(b"ecdsa-sha2-"):
1514
1515 for curve_name, curve in _curves.items():
1516 if curve.openssh is None:
1517 continue
1518 if not curve.openssh.startswith("ecdsa-sha2"):
1519 continue
1520 middle = tobytes(curve.openssh.split("-")[2])
1521 if keyparts[1] == middle:
1522 break
1523 else:
1524 raise ValueError("Unsupported ECC curve: " + middle)
1525
1526 ecc_key = _import_public_der(keyparts[2], curve_oid=curve.oid)
1527
1528 # EdDSA
1529 elif parts[0] == b"ssh-ed25519":
1530 x, y = _import_ed25519_public_key(keyparts[1])
1531 ecc_key = construct(curve="Ed25519", point_x=x, point_y=y)
1532 else:
1533 raise ValueError("Unsupported SSH key type: " + parts[0])
1534
1535 except (IndexError, TypeError, binascii.Error):
1536 raise ValueError("Error parsing SSH key type: " + parts[0])
1537
1538 return ecc_key
1539
1540
1541 def _import_openssh_private_ecc(data, password):
1542
1543 from ._openssh import (import_openssh_private_generic,
1544 read_bytes, read_string, check_padding)
1545
1546 key_type, decrypted = import_openssh_private_generic(data, password)
1547
1548 eddsa_keys = {
1549 "ssh-ed25519": ("Ed25519", _import_ed25519_public_key, 32),
1550 }
1551
1552 # https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent-04
1553 if key_type.startswith("ecdsa-sha2"):
1554
1555 ecdsa_curve_name, decrypted = read_string(decrypted)
1556 if ecdsa_curve_name not in _curves:
1557 raise UnsupportedEccFeature("Unsupported ECC curve %s" % ecdsa_curve_name)
1558 curve = _curves[ecdsa_curve_name]
1559 modulus_bytes = (curve.modulus_bits + 7) // 8
1560
1561 public_key, decrypted = read_bytes(decrypted)
1562
1563 if bord(public_key[0]) != 4:
1564 raise ValueError("Only uncompressed OpenSSH EC keys are supported")
1565 if len(public_key) != 2 * modulus_bytes + 1:
1566 raise ValueError("Incorrect public key length")
1567
1568 point_x = Integer.from_bytes(public_key[1:1+modulus_bytes])
1569 point_y = Integer.from_bytes(public_key[1+modulus_bytes:])
1570
1571 private_key, decrypted = read_bytes(decrypted)
1572 d = Integer.from_bytes(private_key)
1573
1574 params = {'d': d, 'curve': ecdsa_curve_name}
1575
1576 elif key_type in eddsa_keys:
1577
1578 curve_name, import_eddsa_public_key, seed_len = eddsa_keys[key_type]
1579
1580 public_key, decrypted = read_bytes(decrypted)
1581 point_x, point_y = import_eddsa_public_key(public_key)
1582
1583 private_public_key, decrypted = read_bytes(decrypted)
1584 seed = private_public_key[:seed_len]
1585
1586 params = {'seed': seed, 'curve': curve_name}
1587 else:
1588 raise ValueError("Unsupport SSH agent key type:" + key_type)
1589
1590 _, padded = read_string(decrypted) # Comment
1591 check_padding(padded)
1592
1593 return construct(point_x=point_x, point_y=point_y, **params)
1594
1595
1596 def _import_ed25519_public_key(encoded):
1597 """Import an Ed25519 ECC public key, encoded as raw bytes as described
1598 in RFC8032_.
1599
1600 Args:
1601 encoded (bytes):
1602 The Ed25519 public key to import. It must be 32 bytes long.
1603
1604 Returns:
1605 :class:`EccKey` : a new ECC key object
1606
1607 Raises:
1608 ValueError: when the given key cannot be parsed.
1609
1610 .. _RFC8032: https://datatracker.ietf.org/doc/html/rfc8032
1611 """
1612
1613 if len(encoded) != 32:
1614 raise ValueError("Incorrect length. Only Ed25519 public keys are supported.")
1615
1616 p = Integer(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed) # 2**255 - 19
1617 d = 37095705934669439343138083508754565189542113879843219016388785533085940283555
1618
1619 y = bytearray(encoded)
1620 x_lsb = y[31] >> 7
1621 y[31] &= 0x7F
1622 point_y = Integer.from_bytes(y, byteorder='little')
1623 if point_y >= p:
1624 raise ValueError("Invalid Ed25519 key (y)")
1625 if point_y == 1:
1626 return 0, 1
1627
1628 u = (point_y**2 - 1) % p
1629 v = ((point_y**2 % p) * d + 1) % p
1630 try:
1631 v_inv = v.inverse(p)
1632 x2 = (u * v_inv) % p
1633 point_x = Integer._tonelli_shanks(x2, p)
1634 if (point_x & 1) != x_lsb:
1635 point_x = p - point_x
1636 except ValueError:
1637 raise ValueError("Invalid Ed25519 public key")
1638 return point_x, point_y
1639
1640
1641 def _import_ed448_public_key(encoded):
1642 """Import an Ed448 ECC public key, encoded as raw bytes as described
1643 in RFC8032_.
1644
1645 Args:
1646 encoded (bytes):
1647 The Ed448 public key to import. It must be 57 bytes long.
1648
1649 Returns:
1650 :class:`EccKey` : a new ECC key object
1651
1652 Raises:
1653 ValueError: when the given key cannot be parsed.
1654
1655 .. _RFC8032: https://datatracker.ietf.org/doc/html/rfc8032
1656 """
1657
1658 if len(encoded) != 57:
1659 raise ValueError("Incorrect length. Only Ed448 public keys are supported.")
1660
1661 p = Integer(0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffff) # 2**448 - 2**224 - 1
1662 d = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffff6756
1663
1664 y = encoded[:56]
1665 x_lsb = bord(encoded[56]) >> 7
1666 point_y = Integer.from_bytes(y, byteorder='little')
1667 if point_y >= p:
1668 raise ValueError("Invalid Ed448 key (y)")
1669 if point_y == 1:
1670 return 0, 1
1671
1672 u = (point_y**2 - 1) % p
1673 v = ((point_y**2 % p) * d - 1) % p
1674 try:
1675 v_inv = v.inverse(p)
1676 x2 = (u * v_inv) % p
1677 point_x = Integer._tonelli_shanks(x2, p)
1678 if (point_x & 1) != x_lsb:
1679 point_x = p - point_x
1680 except ValueError:
1681 raise ValueError("Invalid Ed448 public key")
1682 return point_x, point_y
1683
1684
1685 def import_key(encoded, passphrase=None, curve_name=None):
1686 """Import an ECC key (public or private).
1687
1688 Args:
1689 encoded (bytes or multi-line string):
1690 The ECC key to import.
1691 The function will try to automatically detect the right format.
1692
1693 Supported formats for an ECC **public** key:
1694
1695 * X.509 certificate: binary (DER) or ASCII (PEM).
1696 * X.509 ``subjectPublicKeyInfo``: binary (DER) or ASCII (PEM).
1697 * SEC1_ (or X9.62), as ``bytes``. NIST P curves only.
1698 You must also provide the ``curve_name`` (with a value from the `ECC table`_)
1699 * OpenSSH line, defined in RFC5656_ and RFC8709_ (ASCII).
1700 This is normally the content of files like ``~/.ssh/id_ecdsa.pub``.
1701
1702 Supported formats for an ECC **private** key:
1703
1704 * A binary ``ECPrivateKey`` structure, as defined in `RFC5915`_ (DER).
1705 NIST P curves only.
1706 * A `PKCS#8`_ structure (or the more recent Asymmetric Key Package, RFC5958_): binary (DER) or ASCII (PEM).
1707 * `OpenSSH 6.5`_ and newer versions (ASCII).
1708
1709 Private keys can be in the clear or password-protected.
1710
1711 For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
1712
1713 passphrase (byte string):
1714 The passphrase to use for decrypting a private key.
1715 Encryption may be applied protected at the PEM level (not recommended)
1716 or at the PKCS#8 level (recommended).
1717 This parameter is ignored if the key in input is not encrypted.
1718
1719 curve_name (string):
1720 For a SEC1 encoding only. This is the name of the curve,
1721 as defined in the `ECC table`_.
1722
1723 .. note::
1724
1725 To import EdDSA private and public keys, when encoded as raw ``bytes``, use:
1726
1727 * :func:`Crypto.Signature.eddsa.import_public_key`, or
1728 * :func:`Crypto.Signature.eddsa.import_private_key`.
1729
1730 Returns:
1731 :class:`EccKey` : a new ECC key object
1732
1733 Raises:
1734 ValueError: when the given key cannot be parsed (possibly because
1735 the pass phrase is wrong).
1736
1737 .. _RFC1421: https://datatracker.ietf.org/doc/html/rfc1421
1738 .. _RFC1423: https://datatracker.ietf.org/doc/html/rfc1423
1739 .. _RFC5915: https://datatracker.ietf.org/doc/html/rfc5915
1740 .. _RFC5656: https://datatracker.ietf.org/doc/html/rfc5656
1741 .. _RFC8709: https://datatracker.ietf.org/doc/html/rfc8709
1742 .. _RFC5958: https://datatracker.ietf.org/doc/html/rfc5958
1743 .. _`PKCS#8`: https://datatracker.ietf.org/doc/html/rfc5208
1744 .. _`OpenSSH 6.5`: https://flak.tedunangst.com/post/new-openssh-key-format-and-bcrypt-pbkdf
1745 .. _SEC1: https://www.secg.org/sec1-v2.pdf
1746 """
1747
1748 from Crypto.IO import PEM
1749
1750 encoded = tobytes(encoded)
1751 if passphrase is not None:
1752 passphrase = tobytes(passphrase)
1753
1754 # PEM
1755 if encoded.startswith(b'-----BEGIN OPENSSH PRIVATE KEY'):
1756 text_encoded = tostr(encoded)
1757 openssh_encoded, marker, enc_flag = PEM.decode(text_encoded, passphrase)
1758 result = _import_openssh_private_ecc(openssh_encoded, passphrase)
1759 return result
1760
1761 elif encoded.startswith(b'-----'):
1762
1763 text_encoded = tostr(encoded)
1764
1765 # Remove any EC PARAMETERS section
1766 # Ignore its content because the curve type must be already given in the key
1767 ecparams_start = "-----BEGIN EC PARAMETERS-----"
1768 ecparams_end = "-----END EC PARAMETERS-----"
1769 text_encoded = re.sub(ecparams_start + ".*?" + ecparams_end, "",
1770 text_encoded,
1771 flags=re.DOTALL)
1772
1773 der_encoded, marker, enc_flag = PEM.decode(text_encoded, passphrase)
1774 if enc_flag:
1775 passphrase = None
1776 try:
1777 result = _import_der(der_encoded, passphrase)
1778 except UnsupportedEccFeature as uef:
1779 raise uef
1780 except ValueError:
1781 raise ValueError("Invalid DER encoding inside the PEM file")
1782 return result
1783
1784 # OpenSSH
1785 if encoded.startswith((b'ecdsa-sha2-', b'ssh-ed25519')):
1786 return _import_openssh_public(encoded)
1787
1788 # DER
1789 if len(encoded) > 0 and bord(encoded[0]) == 0x30:
1790 return _import_der(encoded, passphrase)
1791
1792 # SEC1
1793 if len(encoded) > 0 and bord(encoded[0]) in (0x02, 0x03, 0x04):
1794 if curve_name is None:
1795 raise ValueError("No curve name was provided")
1796 return _import_public_der(encoded, curve_name=curve_name)
1797
1798 raise ValueError("ECC key format is not supported")
1799
1800
1801 if __name__ == "__main__":
1802
1803 import time
1804
1805 d = 0xc51e4753afdec1e6b6c6a5b992f43f8dd0c7a8933072708b6522468b2ffb06fd
1806
1807 point = _curves['p256'].G.copy()
1808 count = 3000
1809
1810 start = time.time()
1811 for x in range(count):
1812 pointX = point * d
1813 print("(P-256 G)", (time.time() - start) / count * 1000, "ms")
1814
1815 start = time.time()
1816 for x in range(count):
1817 pointX = pointX * d
1818 print("(P-256 arbitrary point)", (time.time() - start) / count * 1000, "ms")