-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathutil.py
281 lines (216 loc) · 7.8 KB
/
util.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
#!/usr/bin/python
#
# utilities for BLS sigs Python ref impl
from binascii import hexlify, unhexlify
from enum import Enum, unique
import getopt
import os
import struct
import sys
from consts import q
from curve_ops import g1gen, g2gen, from_jacobian
from serdesZ import serialize, deserialize, SerError, DeserError
@unique
class SigType(Enum):
basic = 1
message_augmentation = 2
proof_of_possession = 3
def __bytes__(self):
if self is SigType.basic:
return b'NUL'
if self is SigType.message_augmentation:
return b'AUG'
if self is SigType.proof_of_possession:
return b'POP'
raise RuntimeError("unknown SigType")
class Options(object):
run_tests = False
test_inputs = None
verify = False
quiet = False
gen_vectors = False
sigtype = SigType.basic
def __init__(self):
self.test_inputs = []
def _read_test_file(filename):
ret = []
with open(filename, "r") as test_file:
ret += [ tuple( unhexlify(val) for val in line.strip().split(' ') ) for line in test_file.readlines() ]
return ret
def get_cmdline_options():
sk = bytes("11223344556677889900112233445566", "ascii")
msg_dflt = bytes("the message to be signed", "ascii")
ret = Options()
# process cmdline args with getopt
try:
(opts, args) = getopt.gnu_getopt(sys.argv[1:], "k:T:tvqBAPg")
except getopt.GetoptError as err:
print("Usage: %s [-gqtv] [-k key] [-T test_file] [-B | -A | -P] [msg ...]" % sys.argv[0])
sys.exit(str(err))
for (opt, arg) in opts:
if opt == "-k":
sk = os.fsencode(arg)
elif opt == "-T":
ret.test_inputs += _read_test_file(arg)
elif opt == "-t":
ret.run_tests = True
elif opt == "-v":
ret.verify = True
elif opt == "-q":
ret.quiet = True
elif opt == "-B":
ret.sigtype = SigType.basic
elif opt == "-A":
ret.sigtype = SigType.message_augmentation
elif opt == "-P":
ret.sigtype = SigType.proof_of_possession
elif opt == "-g":
ret.gen_vectors = True
else:
raise RuntimeError("got unexpected option %s from getopt" % opt)
# build up return value: (msg, sk) tuples from cmdline and test files
ret.test_inputs += [ (os.fsencode(arg), sk) for arg in args ]
if not ret.test_inputs:
ret.test_inputs = [ (msg_dflt, sk) ]
return ret
def print_g1_hex(P, margin=8):
indent_str = " " * margin
if len(P) == 3:
P = from_jacobian(P)
print(indent_str, "x = 0x%x" % P[0])
print(indent_str, "y = 0x%x" % P[1])
def print_f2_hex(vv, name, margin=8):
indent_str = " " * margin
print(indent_str + name + "0 = 0x%x" % vv[0])
print(indent_str + name + "1 = 0x%x" % vv[1])
def print_g2_hex(P, margin=8):
if len(P) == 3:
P = from_jacobian(P)
print_f2_hex(P[0], 'x', margin)
print_f2_hex(P[1], 'y', margin)
def print_value(iv, indent=8, skip_first=False):
max_line_length = 111
if isinstance(iv, str):
cs = struct.unpack("=" + "B" * len(iv), iv)
elif isinstance(iv, (list, bytes)):
cs = iv
else:
cs = [iv]
line_length = indent
indent_string = " " * indent
if not skip_first:
sys.stdout.write(indent_string)
for c in cs:
out_str = "0x%02x" % c
if line_length + len(out_str) > max_line_length:
sys.stdout.write("\n%s" % indent_string)
line_length = indent
sys.stdout.write(out_str + " ")
line_length += len(out_str) + 1
sys.stdout.write("\n")
def print_tv_hash(hash_in, ciphersuite, hash_fn, print_pt_fn, is_ell2, opts):
if len(hash_in) > 2:
(msg, _, hash_expect) = hash_in[:3]
else:
msg = hash_in[0]
hash_expect = None
# hash to point
P = hash_fn(msg, ciphersuite)
if opts.gen_vectors:
print(b' '.join( hexlify(v) for v in (msg, b'\x00', serialize(P)) ).decode('ascii'))
return
if hash_expect is not None:
if serialize(P) != hash_expect:
raise SerError("serializing P did not give hash_expect")
if from_jacobian(deserialize(hash_expect, is_ell2)) != from_jacobian(P):
raise DeserError("deserializing hash_expect did not give P")
if opts.quiet:
return
print("=============== begin hash test vector ==================")
sys.stdout.write("ciphersuite: ")
print_value(ciphersuite, 13, True)
sys.stdout.write("message: ")
print_value(msg, 13, True)
print("result:")
print_pt_fn(P)
print("=============== end hash test vector ==================")
def print_tv_sig(sig_in, ciphersuite, sign_fn, keygen_fn, print_pk_fn, print_sig_fn, ver_fn, is_ell2, opts):
if len(sig_in) > 2:
(msg, sk, sig_expect) = sig_in[:3]
else:
(msg, sk) = sig_in
sig_expect = None
# generate key and signature
(x_prime, pk) = keygen_fn(sk)
sig = sign_fn(x_prime, msg, ciphersuite)
if ver_fn is not None and not ver_fn(pk, sig, msg, ciphersuite):
raise RuntimeError("verifying generated signature failed")
if opts.gen_vectors:
print(b' '.join( hexlify(v) for v in (msg, sk, serialize(sig)) ).decode('ascii'))
return
if sig_expect is not None:
if serialize(sig) != sig_expect:
raise SerError("serializing sig did not give sig_expect")
if from_jacobian(deserialize(sig_expect, is_ell2)) != from_jacobian(sig):
raise DeserError("deserializing sig_expect did not give sig")
if opts.quiet:
return
# output the test vector
print("================== begin test vector ====================")
print("g1 generator:")
print_g1_hex(g1gen)
print("g2 generator:")
print_g2_hex(g2gen)
print("group order: 0x%x" % q)
sys.stdout.write("ciphersuite: ")
print_value(ciphersuite, 13, True)
sys.stdout.write("message: ")
print_value(msg, 13, True)
sys.stdout.write("sk: ")
print_value(sk, 13, True)
sys.stdout.write("x_prime: ")
print_value(x_prime, 13, True)
print("public key:")
print_pk_fn(pk)
print("signature:")
print_sig_fn(sig)
print("================== end test vector ====================")
def print_tv_pop(sig_in, ciphersuite, sign_fn, keygen_fn, print_pk_fn, print_sig_fn, ver_fn, is_ell2, opts):
if len(sig_in) > 2:
(_, sk, sig_expect) = sig_in[:3]
else:
(_, sk) = sig_in
sig_expect = None
# generate key and signature
(x_prime, pk) = keygen_fn(sk)
sig = sign_fn(x_prime, pk, ciphersuite)
if ver_fn is not None and not ver_fn(pk, sig, ciphersuite):
raise RuntimeError("verifying generated signature failed")
if opts.gen_vectors:
print(b' '.join( hexlify(v) for v in (b'\x00', sk, serialize(sig)) ).decode('ascii'))
return
if sig_expect is not None:
if serialize(sig) != sig_expect:
raise SerError("serializing sig did not give sig_expect")
if from_jacobian(deserialize(sig_expect, is_ell2)) != from_jacobian(sig):
raise DeserError("deserializing sig_expect did not give sig")
if opts.quiet:
return
# output the test vector
print("================== begin test vector ====================")
print("g1 generator:")
print_g1_hex(g1gen)
print("g2 generator:")
print_g2_hex(g2gen)
print("group order: 0x%x" % q)
sys.stdout.write("ciphersuite: ")
print_value(ciphersuite, 13, True)
sys.stdout.write("sk: ")
print_value(sk, 13, True)
sys.stdout.write("x_prime: ")
print_value(x_prime, 13, True)
print("public key:")
print_pk_fn(pk)
print("signature:")
print_sig_fn(sig)
print("================== end test vector ====================")