This repository has been archived by the owner on Jan 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 86
/
expand_libecc.py
1948 lines (1826 loc) · 78.6 KB
/
expand_libecc.py
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#/*
# * Copyright (C) 2017 - This file is part of libecc project
# *
# * Authors:
# * Ryad BENADJILA <ryadbenadjila@gmail.com>
# * Arnaud EBALARD <arnaud.ebalard@ssi.gouv.fr>
# * Jean-Pierre FLORI <jean-pierre.flori@ssi.gouv.fr>
# *
# * Contributors:
# * Nicolas VIVET <nicolas.vivet@ssi.gouv.fr>
# * Karim KHALFALLAH <karim.khalfallah@ssi.gouv.fr>
# *
# * This software is licensed under a dual BSD and GPL v2 license.
# * See LICENSE file at the root folder of the project.
# */
#! /usr/bin/env python
import random, sys, re, math, os, getopt, glob, copy, hashlib, binascii, string, signal, base64
# External dependecy for SHA-3
# It is an independent module, since hashlib has no support
# for SHA-3 functions for now
import sha3
# Handle Python 2/3 issues
def is_python_2():
if sys.version_info[0] < 3:
return True
else:
return False
### Ctrl-C handler
def handler(signal, frame):
print("\nSIGINT caught: exiting ...")
exit(0)
# Helper to ask the user for something
def get_user_input(prompt):
# Handle the Python 2/3 issue
if is_python_2() == False:
return input(prompt)
else:
return raw_input(prompt)
##########################################################
#### Math helpers
def egcd(b, n):
x0, x1, y0, y1 = 1, 0, 0, 1
while n != 0:
q, b, n = b // n, n, b % n
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
return b, x0, y0
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception("Error: modular inverse does not exist")
else:
return x % m
def compute_monty_coef(prime, pbitlen, wlen):
"""
Compute montgomery coeff r, r^2 and mpinv. pbitlen is the size
of p in bits. It is expected to be a multiple of word
bit size.
"""
r = (1 << int(pbitlen)) % prime
r_square = (1 << (2 * int(pbitlen))) % prime
mpinv = 2**wlen - (modinv(prime, 2**wlen))
return r, r_square, mpinv
def compute_div_coef(prime, pbitlen, wlen):
"""
Compute division coeffs p_normalized, p_shift and p_reciprocal.
"""
tmp = prime
cnt = 0
while tmp != 0:
tmp = tmp >> 1
cnt += 1
pshift = int(pbitlen - cnt)
primenorm = prime << pshift
B = 2**wlen
prec = B**3 // ((primenorm >> int(pbitlen - 2*wlen)) + 1) - B
return pshift, primenorm, prec
def is_probprime(n):
# ensure n is odd
if n % 2 == 0:
return False
# write n-1 as 2**s * d
# repeatedly try to divide n-1 by 2
s = 0
d = n-1
while True:
quotient, remainder = divmod(d, 2)
if remainder == 1:
break
s += 1
d = quotient
assert(2**s * d == n-1)
# test the base a to see whether it is a witness for the compositeness of n
def try_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True # n is definitely composite
for i in range(5):
a = random.randrange(2, n)
if try_composite(a):
return False
return True # no base tested showed n as composite
def legendre_symbol(a, p):
ls = pow(a, (p - 1) // 2, p)
return -1 if ls == p - 1 else ls
# Tonelli-Shanks algorithm to find square roots
# over prime fields
def mod_sqrt(a, p):
# Square root of 0 is 0
if a == 0:
return 0
# Simple cases
if legendre_symbol(a, p) != 1:
# No square residue
return None
elif p == 2:
return a
elif p % 4 == 3:
return pow(a, (p + 1) // 4, p)
s = p - 1
e = 0
while s % 2 == 0:
s = s // 2
e += 1
n = 2
while legendre_symbol(n, p) != -1:
n += 1
x = pow(a, (s + 1) // 2, p)
b = pow(a, s, p)
g = pow(n, s, p)
r = e
while True:
t = b
m = 0
if is_python_2():
for m in xrange(r):
if t == 1:
break
t = pow(t, 2, p)
else:
for m in range(r):
if t == 1:
break
t = pow(t, 2, p)
if m == 0:
return x
gs = pow(g, 2 ** (r - m - 1), p)
g = (gs * gs) % p
x = (x * gs) % p
b = (b * g) % p
r = m
##########################################################
### Math elliptic curves basic blocks
# WARNING: these blocks are only here for testing purpose and
# are not intended to be used in a security oriented library!
# This explains the usage of naive affine coordinates fomulas
class Curve(object):
def __init__(self, a, b, prime, order, cofactor, gx, gy, npoints, name, oid):
self.a = a
self.b = b
self.p = prime
self.q = order
self.c = cofactor
self.gx = gx
self.gy = gy
self.n = npoints
self.name = name
self.oid = oid
# Equality testing
def __eq__(self, other):
return self.__dict__ == other.__dict__
# Deep copy is implemented using the ~X operator
def __invert__(self):
return copy.deepcopy(self)
class Point(object):
# Affine coordinates (x, y), infinity point is (None, None)
def __init__(self, curve, x, y):
self.curve = curve
if x != None:
self.x = (x % curve.p)
else:
self.x = None
if y != None:
self.y = (y % curve.p)
else:
self.y = None
# Check that the point is indeed on the curve
if (x != None):
if (pow(y, 2, curve.p) != ((pow(x, 3, curve.p) + (curve.a * x) + curve.b ) % curve.p)):
raise Exception("Error: point is not on curve!")
# Addition
def __add__(self, Q):
x1 = self.x
y1 = self.y
x2 = Q.x
y2 = Q.y
curve = self.curve
# Check that we are on the same curve
if Q.curve != curve:
raise Exception("Point add error: two point don't have the same curve")
# If Q is infinity point, return ourself
if Q.x == None:
return Point(self.curve, self.x, self.y)
# If we are the infinity point return Q
if self.x == None:
return Q
# Infinity point or Doubling
if (x1 == x2):
if (((y1 + y2) % curve.p) == 0):
# Return infinity point
return Point(self.curve, None, None)
else:
# Doubling
L = ((3*pow(x1, 2, curve.p) + curve.a) * modinv(2*y1, curve.p)) % curve.p
# Addition
else:
L = ((y2 - y1) * modinv((x2 - x1) % curve.p, curve.p)) % curve.p
resx = (pow(L, 2, curve.p) - x1 - x2) % curve.p
resy = ((L * (x1 - resx)) - y1) % curve.p
# Return the point
return Point(self.curve, resx, resy)
# Negation
def __neg__(self):
if (self.x == None):
return Point(self.curve, None, None)
else:
return Point(self.curve, self.x, -self.y)
# Subtraction
def __sub__(self, other):
return self + (-other)
# Scalar mul
def __rmul__(self, scalar):
# Implement simple double and add algorithm
P = self
Q = Point(P.curve, None, None)
for i in range(getbitlen(scalar), 0, -1):
Q = Q + Q
if (scalar >> (i-1)) & 0x1 == 0x1:
Q = Q + P
return Q
# Equality testing
def __eq__(self, other):
return self.__dict__ == other.__dict__
# Deep copy is implemented using the ~X operator
def __invert__(self):
return copy.deepcopy(self)
def __str__(self):
if self.x == None:
return "Inf"
else:
return ("(x = %s, y = %s)" % (hex(self.x), hex(self.y)))
##########################################################
### Private and public keys structures
class PrivKey(object):
def __init__(self, curve, x):
self.curve = curve
self.x = x
class PubKey(object):
def __init__(self, curve, Y):
# Sanity check
if Y.curve != curve:
raise Exception("Error: curve and point curve differ in public key!")
self.curve = curve
self.Y = Y
class KeyPair(object):
def __init__(self, pubkey, privkey):
self.pubkey = pubkey
self.privkey = privkey
def fromprivkey(privkey, is_eckcdsa=False):
curve = privkey.curve
q = curve.q
gx = curve.gx
gy = curve.gy
G = Point(curve, gx, gy)
if is_eckcdsa == False:
return PubKey(curve, privkey.x * G)
else:
return PubKey(curve, modinv(privkey.x, q) * G)
def genKeyPair(curve, is_eckcdsa=False):
p = curve.p
q = curve.q
gx = curve.gx
gy = curve.gy
G = Point(curve, gx, gy)
OK = False
while OK == False:
x = getrandomint(q)
if x == 0:
continue
OK = True
privkey = PrivKey(curve, x)
pubkey = fromprivkey(privkey, is_eckcdsa)
return KeyPair(pubkey, privkey)
##########################################################
### Signature algorithms helpers
def getrandomint(modulo):
return random.randrange(0, modulo+1)
def getbitlen(bint):
"""
Returns the number of bits encoding an integer
"""
if bint == None:
return 0
if bint == 0:
# Zero is encoded on one bit
return 1
else:
return int(bint).bit_length()
def getbytelen(bint):
"""
Returns the number of bytes encoding an integer
"""
bitsize = getbitlen(bint)
bytesize = int(bitsize // 8)
if bitsize % 8 != 0:
bytesize += 1
return bytesize
def stringtoint(bitstring):
acc = 0
size = len(bitstring)
for i in range(0, size):
acc = acc + (ord(bitstring[i]) * (2**(8*(size - 1 - i))))
return acc
def inttostring(a):
size = int(getbytelen(a))
outstr = ""
for i in range(0, size):
outstr = outstr + chr((a >> (8*(size - 1 - i))) & 0xFF)
return outstr
def expand(bitstring, bitlen, direction):
bytelen = int(math.ceil(bitlen / 8.))
if len(bitstring) >= bytelen:
return bitstring
else:
if direction == "LEFT":
return ((bytelen-len(bitstring))*"\x00") + bitstring
elif direction == "RIGHT":
return bitstring + ((bytelen-len(bitstring))*"\x00")
else:
raise Exception("Error: unknown direction "+direction+" in expand")
def truncate(bitstring, bitlen, keep):
"""
Takes a bit string and truncates it to keep the left
most or the right most bits
"""
strbitlen = 8*len(bitstring)
# Check if truncation is needed
if strbitlen > bitlen:
if keep == "LEFT":
return expand(inttostring(stringtoint(bitstring) >> int(strbitlen - bitlen)), bitlen, "LEFT")
elif keep == "RIGHT":
mask = (2**bitlen)-1
return expand(inttostring(stringtoint(bitstring) & mask), bitlen, "LEFT")
else:
raise Exception("Error: unknown direction "+keep+" in truncate")
else:
# No need to truncate!
return bitstring
##########################################################
### Hash algorithms
def sha224(message):
ctx = hashlib.sha224()
if(is_python_2() == True):
ctx.update(message)
digest = ctx.digest()
else:
ctx.update(message.encode('latin-1'))
digest = ctx.digest().decode('latin-1')
return (digest, ctx.digest_size, ctx.block_size)
def sha256(message):
ctx = hashlib.sha256()
if(is_python_2() == True):
ctx.update(message)
digest = ctx.digest()
else:
ctx.update(message.encode('latin-1'))
digest = ctx.digest().decode('latin-1')
return (digest, ctx.digest_size, ctx.block_size)
def sha384(message):
ctx = hashlib.sha384()
if(is_python_2() == True):
ctx.update(message)
digest = ctx.digest()
else:
ctx.update(message.encode('latin-1'))
digest = ctx.digest().decode('latin-1')
return (digest, ctx.digest_size, ctx.block_size)
def sha512(message):
ctx = hashlib.sha512()
if(is_python_2() == True):
ctx.update(message)
digest = ctx.digest()
else:
ctx.update(message.encode('latin-1'))
digest = ctx.digest().decode('latin-1')
return (digest, ctx.digest_size, ctx.block_size)
def sha3_224(message):
ctx = sha3.Sha3_ctx(224)
if(is_python_2() == True):
ctx.update(message)
digest = ctx.digest()
else:
ctx.update(message.encode('latin-1'))
digest = ctx.digest().decode('latin-1')
return (digest, ctx.digest_size, ctx.block_size)
def sha3_256(message):
ctx = sha3.Sha3_ctx(256)
if(is_python_2() == True):
ctx.update(message)
digest = ctx.digest()
else:
ctx.update(message.encode('latin-1'))
digest = ctx.digest().decode('latin-1')
return (digest, ctx.digest_size, ctx.block_size)
def sha3_384(message):
ctx = sha3.Sha3_ctx(384)
if(is_python_2() == True):
ctx.update(message)
digest = ctx.digest()
else:
ctx.update(message.encode('latin-1'))
digest = ctx.digest().decode('latin-1')
return (digest, ctx.digest_size, ctx.block_size)
def sha3_512(message):
ctx = sha3.Sha3_ctx(512)
if(is_python_2() == True):
ctx.update(message)
digest = ctx.digest()
else:
ctx.update(message.encode('latin-1'))
digest = ctx.digest().decode('latin-1')
return (digest, ctx.digest_size, ctx.block_size)
##########################################################
### Signature algorithms
# *| IUF - ECDSA signature
# *|
# *| UF 1. Compute h = H(m)
# *| F 2. If |h| > bitlen(q), set h to bitlen(q)
# *| leftmost (most significant) bits of h
# *| F 3. e = OS2I(h) mod q
# *| F 4. Get a random value k in ]0,q[
# *| F 5. Compute W = (W_x,W_y) = kG
# *| F 6. Compute r = W_x mod q
# *| F 7. If r is 0, restart the process at step 4.
# *| F 8. If e == rx, restart the process at step 4.
# *| F 9. Compute s = k^-1 * (xr + e) mod q
# *| F 10. If s is 0, restart the process at step 4.
# *| F 11. Return (r,s)
def ecdsa_sign(hashfunc, keypair, message, k=None):
privkey = keypair.privkey
# Get important parameters from the curve
p = privkey.curve.p
q = privkey.curve.q
gx = privkey.curve.gx
gy = privkey.curve.gy
G = Point(privkey.curve, gx, gy)
q_limit_len = getbitlen(q)
# Compute the hash
(h, _, _) = hashfunc(message)
# Truncate hash value
h = truncate(h, q_limit_len, "LEFT")
# Convert the hash value to an int
e = stringtoint(h) % q
OK = False
while OK == False:
if k == None:
k = getrandomint(q)
if k == 0:
continue
W = k * G
r = W.x % q
if r == 0:
continue
if e == r * privkey.x:
continue
s = (modinv(k, q) * ((privkey.x * r) + e)) % q
if s == 0:
continue
OK = True
return ((expand(inttostring(r), 8*getbytelen(q), "LEFT") + expand(inttostring(s), 8*getbytelen(q), "LEFT")), k)
# *| IUF - ECDSA verification
# *|
# *| I 1. Reject the signature if r or s is 0.
# *| UF 2. Compute h = H(m)
# *| F 3. If |h| > bitlen(q), set h to bitlen(q)
# *| leftmost (most significant) bits of h
# *| F 4. Compute e = OS2I(h) mod q
# *| F 5. Compute u = (s^-1)e mod q
# *| F 6. Compute v = (s^-1)r mod q
# *| F 7. Compute W' = uG + vY
# *| F 8. If W' is the point at infinity, reject the signature.
# *| F 9. Compute r' = W'_x mod q
# *| F 10. Accept the signature if and only if r equals r'
def ecdsa_verify(hashfunc, keypair, message, sig):
pubkey = keypair.pubkey
# Get important parameters from the curve
p = pubkey.curve.p
q = pubkey.curve.q
gx = pubkey.curve.gx
gy = pubkey.curve.gy
q_limit_len = getbitlen(q)
G = Point(pubkey.curve, gx, gy)
# Extract r and s
if len(sig) != 2*getbytelen(q):
raise Exception("ECDSA verify: bad signature length!")
r = stringtoint(sig[0:int(len(sig)/2)])
s = stringtoint(sig[int(len(sig)/2):])
if r == 0 or s == 0:
return False
# Compute the hash
(h, _, _) = hashfunc(message)
# Truncate hash value
h = truncate(h, q_limit_len, "LEFT")
# Convert the hash value to an int
e = stringtoint(h) % q
u = (modinv(s, q) * e) % q
v = (modinv(s, q) * r) % q
W_ = (u * G) + (v * pubkey.Y)
if W_.x == None:
return False
r_ = W_.x % q
if r == r_:
return True
else:
return False
def eckcdsa_genKeyPair(curve):
return genKeyPair(curve, True)
# *| IUF - ECKCDSA signature
# *|
# *| IUF 1. Compute h = H(z||m)
# *| F 2. If hsize > bitlen(q), set h to bitlen(q)
# *| rightmost (less significant) bits of h.
# *| F 3. Get a random value k in ]0,q[
# *| F 4. Compute W = (W_x,W_y) = kG
# *| F 5. Compute r = h(FE2OS(W_x)).
# *| F 6. If hsize > bitlen(q), set r to bitlen(q)
# *| rightmost (less significant) bits of r.
# *| F 7. Compute e = OS2I(r XOR h) mod q
# *| F 8. Compute s = x(k - e) mod q
# *| F 9. if s == 0, restart at step 3.
# *| F 10. return (r,s)
def eckcdsa_sign(hashfunc, keypair, message, k=None):
privkey = keypair.privkey
# Get important parameters from the curve
p = privkey.curve.p
q = privkey.curve.q
gx = privkey.curve.gx
gy = privkey.curve.gy
G = Point(privkey.curve, gx, gy)
q_limit_len = getbitlen(q)
# Compute the certificate data
(_, _, hblocksize) = hashfunc("")
z = expand(inttostring(keypair.pubkey.Y.x), 8*getbytelen(p), "LEFT")
z = z + expand(inttostring(keypair.pubkey.Y.y), 8*getbytelen(p), "LEFT")
if len(z) > hblocksize:
# Truncate
z = truncate(z, 8*hblocksize, "LEFT")
else:
# Expand
z = expand(z, 8*hblocksize, "RIGHT")
# Compute the hash
(h, _, _) = hashfunc(z + message)
# Truncate hash value
h = truncate(h, q_limit_len, "RIGHT")
OK = False
while OK == False:
if k == None:
k = getrandomint(q)
if k == 0:
continue
W = k * G
(r, _, _) = hashfunc(expand(inttostring(W.x), 8*getbytelen(p), "LEFT"))
r = truncate(r, q_limit_len, "RIGHT")
e = (stringtoint(r) ^ stringtoint(h)) % q
s = (privkey.x * (k - e)) % q
if s == 0:
continue
OK = True
return (r + expand(inttostring(s), 8*getbytelen(q), "LEFT"), k)
# *| IUF - ECKCDSA verification
# *|
# *| I 1. Check the length of r:
# *| - if hsize > bitlen(q), r must be of
# *| length bitlen(q)
# *| - if hsize <= bitlen(q), r must be of
# *| length hsize
# *| I 2. Check that s is in ]0,q[
# *| IUF 3. Compute h = H(z||m)
# *| F 4. If hsize > bitlen(q), set h to bitlen(q)
# *| rightmost (less significant) bits of h.
# *| F 5. Compute e = OS2I(r XOR h) mod q
# *| F 6. Compute W' = sY + eG, where Y is the public key
# *| F 7. Compute r' = h(FE2OS(W'x))
# *| F 8. If hsize > bitlen(q), set r' to bitlen(q)
# *| rightmost (less significant) bits of r'.
# *| F 9. Check if r == r'
def eckcdsa_verify(hashfunc, keypair, message, sig):
pubkey = keypair.pubkey
# Get important parameters from the curve
p = pubkey.curve.p
q = pubkey.curve.q
gx = pubkey.curve.gx
gy = pubkey.curve.gy
G = Point(pubkey.curve, gx, gy)
q_limit_len = getbitlen(q)
(_, hsize, hblocksize) = hashfunc("")
# Extract r and s
if (8*hsize) > q_limit_len:
r_len = int(math.ceil(q_limit_len / 8.))
else:
r_len = hsize
r = stringtoint(sig[0:int(r_len)])
s = stringtoint(sig[int(r_len):])
if (s >= q) or (s < 0):
return False
# Compute the certificate data
z = expand(inttostring(keypair.pubkey.Y.x), 8*getbytelen(p), "LEFT")
z = z + expand(inttostring(keypair.pubkey.Y.y), 8*getbytelen(p), "LEFT")
if len(z) > hblocksize:
# Truncate
z = truncate(z, 8*hblocksize, "LEFT")
else:
# Expand
z = expand(z, 8*hblocksize, "RIGHT")
# Compute the hash
(h, _, _) = hashfunc(z + message)
# Truncate hash value
h = truncate(h, q_limit_len, "RIGHT")
e = (r ^ stringtoint(h)) % q
W_ = (s * pubkey.Y) + (e * G)
(h, _, _) = hashfunc(expand(inttostring(W_.x), 8*getbytelen(p), "LEFT"))
r_ = truncate(h, q_limit_len, "RIGHT")
if stringtoint(r_) == r:
return True
else:
return False
# *| IUF - ECFSDSA signature
# *|
# *| I 1. Get a random value k in ]0,q[
# *| I 2. Compute W = (W_x,W_y) = kG
# *| I 3. Compute r = FE2OS(W_x)||FE2OS(W_y)
# *| I 4. If r is an all zero string, restart the process at step 1.
# *| IUF 5. Compute h = H(r||m)
# *| F 6. Compute e = OS2I(h) mod q
# *| F 7. Compute s = (k + ex) mod q
# *| F 8. If s is 0, restart the process at step 1 (see c. below)
# *| F 9. Return (r,s)
def ecfsdsa_sign(hashfunc, keypair, message, k=None):
privkey = keypair.privkey
# Get important parameters from the curve
p = privkey.curve.p
q = privkey.curve.q
gx = privkey.curve.gx
gy = privkey.curve.gy
G = Point(privkey.curve, gx, gy)
OK = False
while OK == False:
if k == None:
k = getrandomint(q)
if k == 0:
continue
W = k * G
r = expand(inttostring(W.x), 8*getbytelen(p), "LEFT") + expand(inttostring(W.y), 8*getbytelen(p), "LEFT")
if stringtoint(r) == 0:
continue
(h, _, _) = hashfunc(r + message)
e = stringtoint(h) % q
s = (k + e * privkey.x) % q
if s == 0:
continue
OK = True
return (r + expand(inttostring(s), 8*getbytelen(q), "LEFT"), k)
# *| IUF - ECFSDSA verification
# *|
# *| I 1. Reject the signature if r is not a valid point on the curve.
# *| I 2. Reject the signature if s is not in ]0,q[
# *| IUF 3. Compute h = H(r||m)
# *| F 4. Convert h to an integer and then compute e = -h mod q
# *| F 5. compute W' = sG + eY, where Y is the public key
# *| F 6. Compute r' = FE2OS(W'_x)||FE2OS(W'_y)
# *| F 7. Accept the signature if and only if r equals r'
def ecfsdsa_verify(hashfunc, keypair, message, sig):
pubkey = keypair.pubkey
# Get important parameters from the curve
p = pubkey.curve.p
q = pubkey.curve.q
gx = pubkey.curve.gx
gy = pubkey.curve.gy
G = Point(pubkey.curve, gx, gy)
# Extract coordinates from r and s from signature
if len(sig) != (2*getbytelen(p)) + getbytelen(q):
raise Exception("ECFSDSA verify: bad signature length!")
wx = sig[:int(getbytelen(p))]
wy = sig[int(getbytelen(p)):int(2*getbytelen(p))]
r = wx + wy
s = stringtoint(sig[int(2*getbytelen(p)):int((2*getbytelen(p))+getbytelen(q))])
# Check r is on the curve
W = Point(pubkey.curve, stringtoint(wx), stringtoint(wy))
# Check s is in ]0,q[
if s == 0 or s > q:
raise Exception("ECFSDSA verify: s not in ]0,q[")
(h, _, _) = hashfunc(r + message)
e = (-stringtoint(h)) % q
W_ = s * G + e * pubkey.Y
r_ = expand(inttostring(W_.x), 8*getbytelen(p), "LEFT") + expand(inttostring(W_.y), 8*getbytelen(p), "LEFT")
if r == r_:
return True
else:
return False
# NOTE: ISO/IEC 14888-3 standard seems to diverge from the existing implementations
# of ECRDSA when treating the message hash, and from the examples of certificates provided
# in RFC 7091 and draft-deremin-rfc4491-bis. While in ISO/IEC 14888-3 it is explicitely asked
# to proceed with the hash of the message as big endian, the RFCs derived from the Russian
# standard expect the hash value to be treated as little endian when importing it as an integer
# (this discrepancy is exhibited and confirmed by test vectors present in ISO/IEC 14888-3, and
# by X.509 certificates present in the RFCs). This seems (to be confirmed) to be a discrepancy of
# ISO/IEC 14888-3 algorithm description that must be fixed there.
#
# In order to be conservative, libecc uses the Russian standard behavior as expected to be in line with
# other implemetations, but keeps the ISO/IEC 14888-3 behavior if forced/asked by the user using
# the USE_ISO14888_3_ECRDSA toggle. This allows to keep backward compatibility with previous versions of the
# library if needed.
# *| IUF - ECRDSA signature
# *|
# *| UF 1. Compute h = H(m)
# *| F 2. Get a random value k in ]0,q[
# *| F 3. Compute W = (W_x,W_y) = kG
# *| F 4. Compute r = W_x mod q
# *| F 5. If r is 0, restart the process at step 2.
# *| F 6. Compute e = OS2I(h) mod q. If e is 0, set e to 1.
# *| NOTE: here, ISO/IEC 14888-3 and RFCs differ in the way e treated.
# *| e = OS2I(h) for ISO/IEC 14888-3, or e = OS2I(reversed(h)) when endianness of h
# *| is reversed for RFCs.
# *| F 7. Compute s = (rx + ke) mod q
# *| F 8. If s is 0, restart the process at step 2.
# *| F 11. Return (r,s)
def ecrdsa_sign(hashfunc, keypair, message, k=None, use_iso14888_divergence=False):
privkey = keypair.privkey
# Get important parameters from the curve
p = privkey.curve.p
q = privkey.curve.q
gx = privkey.curve.gx
gy = privkey.curve.gy
G = Point(privkey.curve, gx, gy)
(h, _, _) = hashfunc(message)
if use_iso14888_divergence == False:
# Reverse the endianness for Russian standard RFC ECRDSA (contrary to ISO/IEC 14888-3 case)
h = h[::-1]
OK = False
while OK == False:
if k == None:
k = getrandomint(q)
if k == 0:
continue
W = k * G
r = W.x % q
if r == 0:
continue
e = stringtoint(h) % q
if e == 0:
e = 1
s = ((r * privkey.x) + (k * e)) % q
if s == 0:
continue
OK = True
return (expand(inttostring(r), 8*getbytelen(q), "LEFT") + expand(inttostring(s), 8*getbytelen(q), "LEFT"), k)
# *| IUF - ECRDSA verification
# *|
# *| UF 1. Check that r and s are both in ]0,q[
# *| F 2. Compute h = H(m)
# *| F 3. Compute e = OS2I(h)^-1 mod q
# *| NOTE: here, ISO/IEC 14888-3 and RFCs differ in the way e treated.
# *| e = OS2I(h) for ISO/IEC 14888-3, or e = OS2I(reversed(h)) when endianness of h
# *| is reversed for RFCs.
# *| F 4. Compute u = es mod q
# *| F 4. Compute v = -er mod q
# *| F 5. Compute W' = uG + vY = (W'_x, W'_y)
# *| F 6. Let's now compute r' = W'_x mod q
# *| F 7. Check r and r' are the same
def ecrdsa_verify(hashfunc, keypair, message, sig, use_iso14888_divergence=False):
pubkey = keypair.pubkey
# Get important parameters from the curve
p = pubkey.curve.p
q = pubkey.curve.q
gx = pubkey.curve.gx
gy = pubkey.curve.gy
G = Point(pubkey.curve, gx, gy)
# Extract coordinates from r and s from signature
if len(sig) != 2*getbytelen(q):
raise Exception("ECRDSA verify: bad signature length!")
r = stringtoint(sig[:int(getbytelen(q))])
s = stringtoint(sig[int(getbytelen(q)):int(2*getbytelen(q))])
if r == 0 or r > q:
raise Exception("ECRDSA verify: r not in ]0,q[")
if s == 0 or s > q:
raise Exception("ECRDSA verify: s not in ]0,q[")
(h, _, _) = hashfunc(message)
if use_iso14888_divergence == False:
# Reverse the endianness for Russian standard RFC ECRDSA (contrary to ISO/IEC 14888-3 case)
h = h[::-1]
e = modinv(stringtoint(h) % q, q)
u = (e * s) % q
v = (-e * r) % q
W_ = u * G + v * pubkey.Y
r_ = W_.x % q
if r == r_:
return True
else:
return False
# *| IUF - ECGDSA signature
# *|
# *| UF 1. Compute h = H(m). If |h| > bitlen(q), set h to bitlen(q)
# *| leftmost (most significant) bits of h
# *| F 2. Convert e = - OS2I(h) mod q
# *| F 3. Get a random value k in ]0,q[
# *| F 4. Compute W = (W_x,W_y) = kG
# *| F 5. Compute r = W_x mod q
# *| F 6. If r is 0, restart the process at step 4.
# *| F 7. Compute s = x(kr + e) mod q
# *| F 8. If s is 0, restart the process at step 4.
# *| F 9. Return (r,s)
def ecgdsa_sign(hashfunc, keypair, message, k=None):
privkey = keypair.privkey
# Get important parameters from the curve
p = privkey.curve.p
q = privkey.curve.q
gx = privkey.curve.gx
gy = privkey.curve.gy
G = Point(privkey.curve, gx, gy)
(h, _, _) = hashfunc(message)
q_limit_len = getbitlen(q)
# Truncate hash value
h = truncate(h, q_limit_len, "LEFT")
e = (-stringtoint(h)) % q
OK = False
while OK == False:
if k == None:
k = getrandomint(q)
if k == 0:
continue
W = k * G
r = W.x % q
if r == 0:
continue
s = (privkey.x * ((k * r) + e)) % q
if s == 0:
continue
OK = True
return (expand(inttostring(r), 8*getbytelen(q), "LEFT") + expand(inttostring(s), 8*getbytelen(q), "LEFT"), k)
# *| IUF - ECGDSA verification
# *|
# *| I 1. Reject the signature if r or s is 0.
# *| UF 2. Compute h = H(m). If |h| > bitlen(q), set h to bitlen(q)
# *| leftmost (most significant) bits of h
# *| F 3. Compute e = OS2I(h) mod q
# *| F 4. Compute u = ((r^-1)e mod q)
# *| F 5. Compute v = ((r^-1)s mod q)
# *| F 6. Compute W' = uG + vY
# *| F 7. Compute r' = W'_x mod q
# *| F 8. Accept the signature if and only if r equals r'
def ecgdsa_verify(hashfunc, keypair, message, sig):
pubkey = keypair.pubkey
# Get important parameters from the curve
p = pubkey.curve.p
q = pubkey.curve.q
gx = pubkey.curve.gx
gy = pubkey.curve.gy
G = Point(pubkey.curve, gx, gy)
# Extract coordinates from r and s from signature
if len(sig) != 2*getbytelen(q):
raise Exception("ECGDSA verify: bad signature length!")
r = stringtoint(sig[:int(getbytelen(q))])
s = stringtoint(sig[int(getbytelen(q)):int(2*getbytelen(q))])
if r == 0 or r > q:
raise Exception("ECGDSA verify: r not in ]0,q[")
if s == 0 or s > q:
raise Exception("ECGDSA verify: s not in ]0,q[")
(h, _, _) = hashfunc(message)
q_limit_len = getbitlen(q)
# Truncate hash value
h = truncate(h, q_limit_len, "LEFT")
e = stringtoint(h) % q
r_inv = modinv(r, q)
u = (r_inv * e) % q
v = (r_inv * s) % q
W_ = u * G + v * pubkey.Y
r_ = W_.x % q
if r == r_:
return True
else:
return False
# *| IUF - ECSDSA/ECOSDSA signature
# *|
# *| I 1. Get a random value k in ]0, q[
# *| I 2. Compute W = kG = (Wx, Wy)
# *| IUF 3. Compute r = H(Wx [|| Wy] || m)
# *| - In the normal version (ECSDSA), r = h(Wx || Wy || m).
# *| - In the optimized version (ECOSDSA), r = h(Wx || m).
# *| F 4. Compute e = OS2I(r) mod q
# *| F 5. if e == 0, restart at step 1.
# *| F 6. Compute s = (k + ex) mod q.
# *| F 7. if s == 0, restart at step 1.
# *| F 8. Return (r, s)
def ecsdsa_common_sign(hashfunc, keypair, message, optimized, k=None):
privkey = keypair.privkey
# Get important parameters from the curve
p = privkey.curve.p
q = privkey.curve.q
gx = privkey.curve.gx
gy = privkey.curve.gy
G = Point(privkey.curve, gx, gy)
OK = False
while OK == False:
if k == None:
k = getrandomint(q)
if k == 0:
continue
W = k * G
if optimized == False:
(r, _, _) = hashfunc(expand(inttostring(W.x), 8*getbytelen(p), "LEFT") + expand(inttostring(W.y), 8*getbytelen(p), "LEFT") + message)
else:
(r, _, _) = hashfunc(expand(inttostring(W.x), 8*getbytelen(p), "LEFT") + message)
e = stringtoint(r) % q
if e == 0:
continue
s = (k + (e * privkey.x)) % q
if s == 0:
continue
OK = True
return (r + expand(inttostring(s), 8*getbytelen(q), "LEFT"), k)
def ecsdsa_sign(hashfunc, keypair, message, k=None):
return ecsdsa_common_sign(hashfunc, keypair, message, False, k)
def ecosdsa_sign(hashfunc, keypair, message, k=None):
return ecsdsa_common_sign(hashfunc, keypair, message, True, k)
# *| IUF - ECSDSA/ECOSDSA verification
# *|
# *| I 1. if s is not in ]0,q[, reject the signature.x
# *| I 2. Compute e = -r mod q
# *| I 3. If e == 0, reject the signature.
# *| I 4. Compute W' = sG + eY