@@ -304,6 +304,23 @@ def sigencode_der(r, s, order):
304
304
return der .encode_sequence (der .encode_integer (r ), der .encode_integer (s ))
305
305
306
306
307
+ def _canonize (s , order ):
308
+ """
309
+ Internal function for ensuring that the ``s`` value of a signature is in
310
+ the "canonical" format.
311
+
312
+ :param int s: the second parameter of ECDSA signature
313
+ :param int order: the order of the curve over which the signatures was
314
+ computed
315
+
316
+ :return: canonical value of s
317
+ :rtype: int
318
+ """
319
+ if s > order // 2 :
320
+ s = order - s
321
+ return s
322
+
323
+
307
324
def sigencode_strings_canonize (r , s , order ):
308
325
"""
309
326
Encode the signature to a pair of strings in a tuple
@@ -326,8 +343,7 @@ def sigencode_strings_canonize(r, s, order):
326
343
:return: raw encoding of ECDSA signature
327
344
:rtype: tuple(bytes, bytes)
328
345
"""
329
- if s > order / 2 :
330
- s = order - s
346
+ s = _canonize (s , order )
331
347
return sigencode_strings (r , s , order )
332
348
333
349
@@ -350,8 +366,7 @@ def sigencode_string_canonize(r, s, order):
350
366
:return: raw encoding of ECDSA signature
351
367
:rtype: bytes
352
368
"""
353
- if s > order / 2 :
354
- s = order - s
369
+ s = _canonize (s , order )
355
370
return sigencode_string (r , s , order )
356
371
357
372
@@ -381,8 +396,7 @@ def sigencode_der_canonize(r, s, order):
381
396
:return: DER encoding of ECDSA signature
382
397
:rtype: bytes
383
398
"""
384
- if s > order / 2 :
385
- s = order - s
399
+ s = _canonize (s , order )
386
400
return sigencode_der (r , s , order )
387
401
388
402
0 commit comments