-
Notifications
You must be signed in to change notification settings - Fork 17
/
utils.py
436 lines (342 loc) · 13.5 KB
/
utils.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
import dataclasses
import hashlib
import uuid
from enum import Enum
from typing import Union, Optional, Any, List
import attr
import base58
import varint
from authlib.common.encoding import (
to_unicode,
urlsafe_b64decode,
to_bytes,
urlsafe_b64encode,
)
from authlib.jose import ECKey, OKPKey
from authlib.jose.rfc7517 import AsymmetricKey
from didcomm.common.algorithms import SignAlg
from didcomm.common.types import (
VerificationMaterialFormat,
VerificationMethodType,
DID_OR_DID_URL,
DID_URL,
DID,
)
from didcomm.core.serialization import json_str_to_dict
from didcomm.did_doc.did_doc import VerificationMethod
from didcomm.errors import DIDCommValueError
from didcomm.secrets.secrets_resolver import Secret
def id_generator_default() -> str:
return str(uuid.uuid4())
def didcomm_id_generator_default(did: Optional[DID_OR_DID_URL] = None) -> str:
res = id_generator_default()
if did:
res = f"{did}:{res}"
return res
def extract_key(
method: Union[VerificationMethod, Secret], align_kid=False
) -> AsymmetricKey:
if isinstance(method, VerificationMethod):
return _extract_key_from_verification_method(method, align_kid)
else:
return _extract_key_from_secret(method, align_kid)
def _extract_key_from_verification_method(
verification_method: VerificationMethod, align_kid
) -> AsymmetricKey:
if verification_method.type == VerificationMethodType.JSON_WEB_KEY_2020:
jwk = verification_method.public_key_jwk
if align_kid:
jwk["kid"] = verification_method.id
if jwk["kty"] == "EC":
return ECKey.import_key(jwk)
elif jwk["kty"] == "OKP":
return OKPKey.import_key(jwk)
else:
raise DIDCommValueError(f"JWK key type {jwk['kty']} is not supported")
elif verification_method.type in [
VerificationMethodType.X25519_KEY_AGREEMENT_KEY_2019,
VerificationMethodType.ED25519_VERIFICATION_KEY_2018,
]:
raw_value = base58.b58decode(verification_method.public_key_base58)
base64url_value = urlsafe_b64encode(raw_value)
jwk = {
"kty": "OKP",
"crv": "X25519"
if verification_method.type
== VerificationMethodType.X25519_KEY_AGREEMENT_KEY_2019
else "Ed25519",
"x": to_unicode(base64url_value),
}
if align_kid:
jwk["kid"] = verification_method.id
return OKPKey.import_key(jwk)
elif verification_method.type in [
VerificationMethodType.X25519_KEY_AGREEMENT_KEY_2020,
VerificationMethodType.ED25519_VERIFICATION_KEY_2020,
]:
# Currently only base58btc encoding is supported in scope of multibase support
if verification_method.public_key_multibase.startswith("z"):
prefixed_raw_value = base58.b58decode(
verification_method.public_key_multibase[1:]
)
else:
raise DIDCommValueError(
f"Multibase keys containing internally Base58 values only are currently supported "
f"but got the value: {verification_method.public_key_multibase}"
)
codec, raw_value = _from_multicodec(prefixed_raw_value)
expected_codec = (
_Codec.X25519_PUB
if verification_method.type
== VerificationMethodType.X25519_KEY_AGREEMENT_KEY_2020
else _Codec.ED25519_PUB
)
if codec != expected_codec:
raise DIDCommValueError(
f"Multibase public key value contains multicodec prefix "
f"which is inappropriate for verification method type {verification_method.type}"
)
base64url_value = urlsafe_b64encode(raw_value)
jwk = {
"kty": "OKP",
"crv": "X25519"
if verification_method.type
== VerificationMethodType.X25519_KEY_AGREEMENT_KEY_2020
else "Ed25519",
"x": to_unicode(base64url_value),
}
if align_kid:
jwk["kid"] = verification_method.id
return OKPKey.import_key(jwk)
else:
raise DIDCommValueError(
f"Verification method type {verification_method.type} is not supported"
)
_CURVE25519_POINT_SIZE = 32
def _extract_key_from_secret(secret: Secret, align_kid) -> AsymmetricKey:
if secret.type == VerificationMethodType.JSON_WEB_KEY_2020:
if secret.verification_material.format != VerificationMaterialFormat.JWK:
raise DIDCommValueError(
f"Verification material format {secret.verification_material.format} "
f"is not supported for secret type {secret.type}"
)
jwk = json_str_to_dict(secret.verification_material.value)
if align_kid:
jwk["kid"] = secret.kid
if jwk["kty"] == "EC":
return ECKey.import_key(jwk)
elif jwk["kty"] == "OKP":
return OKPKey.import_key(jwk)
else:
raise DIDCommValueError(f"JWK key type {jwk['kty']} is not supported")
elif secret.type in [
VerificationMethodType.X25519_KEY_AGREEMENT_KEY_2019,
VerificationMethodType.ED25519_VERIFICATION_KEY_2018,
]:
if secret.verification_material.format != VerificationMaterialFormat.BASE58:
raise DIDCommValueError(
f"Verification material format {secret.verification_material.format} "
f"is not supported for secret type {secret.type}"
)
raw_value = base58.b58decode(secret.verification_material.value)
raw_d_value = raw_value[:_CURVE25519_POINT_SIZE]
raw_x_value = raw_value[_CURVE25519_POINT_SIZE:]
base64url_d_value = urlsafe_b64encode(raw_d_value)
base64url_x_value = urlsafe_b64encode(raw_x_value)
jwk = {
"kty": "OKP",
"crv": "X25519"
if secret.type == VerificationMethodType.X25519_KEY_AGREEMENT_KEY_2019
else "Ed25519",
"x": to_unicode(base64url_x_value),
"d": to_unicode(base64url_d_value),
}
if align_kid:
jwk["kid"] = secret.kid
return OKPKey.import_key(jwk)
elif secret.type in [
VerificationMethodType.X25519_KEY_AGREEMENT_KEY_2020,
VerificationMethodType.ED25519_VERIFICATION_KEY_2020,
]:
if secret.verification_material.format != VerificationMaterialFormat.MULTIBASE:
raise DIDCommValueError(
f"Verification material format {secret.verification_material.format} "
f"is not supported for secret type {secret.type}"
)
# Currently only base58btc encoding is supported in scope of multibase support
if secret.verification_material.value.startswith("z"):
prefixed_raw_value = base58.b58decode(
secret.verification_material.value[1:]
)
else:
raise DIDCommValueError(
f"Multibase keys containing internally Base58 values only are currently supported "
f"but got the value: {secret.verification_material.value}"
)
codec, raw_value = _from_multicodec(prefixed_raw_value)
expected_codec = (
_Codec.X25519_PRIV
if secret.type == VerificationMethodType.X25519_KEY_AGREEMENT_KEY_2020
else _Codec.ED25519_PRIV
)
if codec != expected_codec:
raise DIDCommValueError(
f"Multibase private key value contains multicodec prefix "
f"which is inappropriate for secret type {secret.type}"
)
raw_d_value = raw_value[:_CURVE25519_POINT_SIZE]
raw_x_value = raw_value[_CURVE25519_POINT_SIZE:]
base64url_d_value = urlsafe_b64encode(raw_d_value)
base64url_x_value = urlsafe_b64encode(raw_x_value)
jwk = {
"kty": "OKP",
"crv": "X25519"
if secret.type == VerificationMethodType.X25519_KEY_AGREEMENT_KEY_2020
else "Ed25519",
"x": to_unicode(base64url_x_value),
"d": to_unicode(base64url_d_value),
}
if align_kid:
jwk["kid"] = secret.kid
return OKPKey.import_key(jwk)
else:
raise DIDCommValueError(f"Secret type {secret.type} is not supported")
class _Codec(Enum):
X25519_PUB = 0xEC
ED25519_PUB = 0xED
ED25519_PRIV = 0x1300
X25519_PRIV = 0x1302
def _from_multicodec(value: bytes) -> (_Codec, bytes):
try:
prefix_int = varint.decode_bytes(value)
except Exception:
raise DIDCommValueError("Invalid multicodec prefix in {}".format(str(value)))
try:
codec = _Codec(prefix_int)
except DIDCommValueError:
raise DIDCommValueError(
"Unknown multicodec prefix {} in {}".format(str(prefix_int), str(value))
)
prefix = varint.encode(prefix_int)
return codec, value[len(prefix) :]
def extract_sign_alg(method: Union[VerificationMethod, Secret]) -> SignAlg:
if method.type == VerificationMethodType.JSON_WEB_KEY_2020:
if isinstance(method, Secret):
if method.verification_material.format != VerificationMaterialFormat.JWK:
raise DIDCommValueError(
f"Verification material format {method.verification_material.format} "
f"is not supported for verification method type {method.type}"
)
jwk = json_str_to_dict(method.verification_material.value)
else:
jwk = method.public_key_jwk # instance of VerificationMethod
if jwk["kty"] == "EC" and jwk["crv"] == "P-256":
return SignAlg.ES256
elif jwk["kty"] == "EC" and jwk["crv"] == "secp256k1":
return SignAlg.ES256K
elif jwk["kty"] == "OKP" and jwk["crv"] == "Ed25519":
return SignAlg.ED25519
else:
raise DIDCommValueError(
f"Keys of {jwk['kty']} type with {jwk['crv']} curve are not supported for signing/verification"
)
elif method.type in [
VerificationMethodType.ED25519_VERIFICATION_KEY_2018,
VerificationMethodType.ED25519_VERIFICATION_KEY_2020,
]:
return SignAlg.ED25519
# elif method.type == VerificationMethodType.ECDSA_SECP_256K1_VERIFICATION_KEY_2019:
# return SignAlg.ES256K
else:
raise DIDCommValueError(
f"Verification method type {method.type} is not supported for signing/verification"
)
# TODO TEST
def is_did(v: Any) -> bool:
# TODO
# - consider other presentations (e.g bytes)
# - strict verifications for parts
# (https://www.w3.org/TR/did-core/#did-syntax)
if isinstance(v, (str, DID)):
parts = str(v).split(":")
return len(parts) >= 3 and parts[0] == "did" and all(parts)
return False
# TODO TEST
def is_did_with_uri_fragment(v: Any) -> bool:
# TODO
# - consider other presentations (e.g bytes)
# - verifications for after-did parts
# (https://www.w3.org/TR/did-core/#did-url-syntax)
if isinstance(v, (str, DID_URL)):
before, sep, after = str(v).partition("#") # always 3-tuple
return sep and after and is_did(before)
return False
# TODO TEST
def is_did_or_did_url(v: Any) -> bool:
return is_did(v) or is_did_with_uri_fragment(v)
def get_did(did_or_did_url: DID_OR_DID_URL) -> DID:
return did_or_did_url.partition("#")[0]
def get_did_and_optionally_kid(did_or_kid: DID_OR_DID_URL) -> (DID, Optional[DID_URL]):
if is_did_with_uri_fragment(did_or_kid):
did = get_did(did_or_kid)
kid = did_or_kid
else:
did = did_or_kid
kid = None
return did, kid
class _Crv(Enum):
ED25519 = "Ed25519"
X25519 = "X25519"
def _get_crv_for_verification_method(
key: Union[VerificationMethod, Secret],
) -> Optional[str]:
if key.type in {
VerificationMethodType.ED25519_VERIFICATION_KEY_2020,
VerificationMethodType.ED25519_VERIFICATION_KEY_2018,
}:
return _Crv.ED25519.value
elif key.type in {
VerificationMethodType.X25519_KEY_AGREEMENT_KEY_2020,
VerificationMethodType.X25519_KEY_AGREEMENT_KEY_2019,
}:
return _Crv.X25519.value
elif key.type is VerificationMethodType.JSON_WEB_KEY_2020:
jwk = (
json_str_to_dict(key.verification_material.value)
if isinstance(key, Secret)
else key.public_key_jwk
)
return jwk["crv"]
else:
return None
def are_keys_compatible(
method1: Union[Secret, VerificationMethod], method2: VerificationMethod
) -> bool:
crv_1 = _get_crv_for_verification_method(method1)
crv_2 = _get_crv_for_verification_method(method2)
if crv_1 is None or crv_2 is None:
return False
return crv_1 == crv_2
def parse_base64url_encoded_json(base64url):
return json_str_to_dict(to_unicode(urlsafe_b64decode(to_bytes(base64url))))
def get_jwe_alg(jwe: dict) -> Optional[str]:
if "protected" not in jwe:
return None
try:
protected = parse_base64url_encoded_json(jwe["protected"])
except Exception:
return None
return protected.get("alg")
def dict_cleanup(d: dict) -> dict:
for k in set(d.keys()):
if d[k] is None:
del d[k]
return d
def dataclass_to_dict(msg) -> dict:
return dict_cleanup(dataclasses.asdict(msg))
def attrs_to_dict(attrs_inst: Any) -> dict:
return dict_cleanup(attr.asdict(attrs_inst))
def calculate_apv(kids: List[DID_URL]) -> str:
return to_unicode(
urlsafe_b64encode(hashlib.sha256(to_bytes(".".join(sorted(kids)))).digest())
)