Skip to content

Commit 892b614

Browse files
committed
fix: address feedback
Signed-off-by: Daniel Bluhm <[email protected]>
1 parent b826282 commit 892b614

File tree

16 files changed

+100
-103
lines changed

16 files changed

+100
-103
lines changed

didcomm_messaging/crypto/backend/askar.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,6 @@ def multikey(self) -> str:
116116
"""Get the key in multibase format."""
117117
return self._multikey
118118

119-
@property
120-
def key_bytes(self) -> bytes:
121-
"""Get the bytes of the key."""
122-
return self.key.get_public_bytes()
123-
124119

125120
class AskarSecretKey(SecretKey):
126121
"""Secret key implementation for Askar."""

didcomm_messaging/crypto/backend/authlib.py

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -56,18 +56,6 @@ def multikey(self) -> str:
5656
"""Return the key in multikey format."""
5757
return self._multikey
5858

59-
@property
60-
def key_bytes(self) -> bytes:
61-
"""Get the bytes of the key."""
62-
jwk = self.key.as_dict(is_private=False)
63-
codec = self.kty_crv_to_codec.get((jwk["kty"], jwk.get("crv")))
64-
65-
if not codec:
66-
raise ValueError("Unsupported key type")
67-
68-
key_bytes = b64url.decode(jwk["x"])
69-
return key_bytes
70-
7159
@classmethod
7260
def key_to_multikey(cls, key: AsymmetricKey) -> str:
7361
"""Convert an Authlib key to a multikey."""

didcomm_messaging/crypto/base.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -69,11 +69,6 @@ def kid(self) -> str:
6969
def multikey(self) -> str:
7070
"""Get the key in multikey format."""
7171

72-
@property
73-
@abstractmethod
74-
def key_bytes(self) -> bytes:
75-
"""Get the bytes of the key."""
76-
7772

7873
class SecretKey(ABC):
7974
"""Secret Key Type."""

didcomm_messaging/messaging.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ class UnpackResult:
4141
"""Result of unpacking a message."""
4242

4343
unpacked: bytes
44-
encrytped: bool
44+
encrypted: bool
4545
authenticated: bool
4646
recipient_kid: str
4747
sender_kid: Optional[str] = None
@@ -139,7 +139,7 @@ async def unpack(
139139
)
140140
return UnpackResult(
141141
unpacked,
142-
encrytped=bool(metadata.method),
142+
encrypted=bool(metadata.method),
143143
authenticated=bool(metadata.sender_kid),
144144
recipient_kid=metadata.recip_key.kid,
145145
sender_kid=metadata.sender_kid,

didcomm_messaging/quickstart.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ async def setup_relay(
258258
await secrets.add_secret(AskarSecretKey(verkey, f"{new_did}#key-1"))
259259
await secrets.add_secret(AskarSecretKey(xkey, f"{new_did}#key-2"))
260260

261-
# V1 formats
261+
# Legacy formats
262262
# verkey
263263
await secrets.add_secret(AskarSecretKey(verkey, doc.authentication[0]))
264264
# xkey

didcomm_messaging/resolver/peer.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,7 @@ class Peer4(DIDResolver):
3232

3333
async def is_resolvable(self, did: str) -> bool:
3434
"""Check to see if a DID is resolvable."""
35-
return bool(peer_4_pattern_short.match(did)) or bool(
36-
peer_4_pattern_long.match(did)
37-
)
35+
return bool(peer_4_pattern_short.match(did) or peer_4_pattern_long.match(did))
3836

3937
async def resolve(self, did: str) -> dict:
4038
"""Resolve a did:peer:4 DID."""

didcomm_messaging/v1/crypto/askar.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@
44
from typing import Optional, Sequence, Tuple, cast
55

66
from base58 import b58decode
7+
import base58
78
from pydid import VerificationMethod
89

910
from didcomm_messaging.crypto.jwe import JweBuilder, JweEnvelope, JweRecipient
1011
from .base import (
1112
V1CryptoService,
12-
V1UnpackResult,
13+
V1CryptoServiceError,
14+
V1CryptoUnpackResult,
1315
RecipData,
1416
)
1517

@@ -24,13 +26,19 @@
2426
class AskarV1CryptoService(V1CryptoService[AskarKey, AskarSecretKey]):
2527
"""V1 crypto service implementation for askar."""
2628

27-
def kid_to_public_key(self, kid: str) -> AskarKey:
29+
def v1_kid_to_public_key(self, kid: str) -> AskarKey:
2830
"""Get a public key from a kid.
2931
3032
In DIDComm v1, kids are the base58 encoded keys.
3133
"""
3234
return AskarKey(Key.from_public_bytes(KeyAlg.ED25519, b58decode(kid)), kid)
3335

36+
def public_key_to_v1_kid(self, key: AskarKey) -> str:
37+
"""Convert a public key into a v1 kid representation."""
38+
if key.key.algorithm != KeyAlg.ED25519:
39+
raise V1CryptoServiceError()
40+
return base58.b58encode(key.key.get_public_bytes()).decode()
41+
3442
@classmethod
3543
def verification_method_to_public_key(cls, vm: VerificationMethod) -> AskarKey:
3644
"""Convert a verification method to a public key."""
@@ -72,8 +80,6 @@ async def pack_message(
7280
)
7381
)
7482
else:
75-
enc_sender = None
76-
nonce = None
7783
enc_cek = crypto_box.crypto_box_seal(target_xk, cek_b)
7884
builder.add_recipient(
7985
JweRecipient(encrypted_key=enc_cek, header={"kid": target_vk.kid})
@@ -97,7 +103,7 @@ async def unpack_message(
97103
wrapper: JweEnvelope,
98104
recip_key: AskarSecretKey,
99105
recip_data: RecipData,
100-
) -> V1UnpackResult:
106+
) -> V1CryptoUnpackResult:
101107
"""Decode a message using the DIDComm v1 'unpack' algorithm."""
102108
payload_key, sender_vk = self._extract_payload_key(recip_key.key, recip_data)
103109

@@ -108,7 +114,7 @@ async def unpack_message(
108114
tag=wrapper.tag,
109115
aad=wrapper.protected_b64,
110116
)
111-
return V1UnpackResult(message, recip_key.kid, sender_vk)
117+
return V1CryptoUnpackResult(message, recip_key.kid, sender_vk)
112118

113119
def _extract_payload_key(
114120
self, recip_key: Key, recip_data: RecipData

didcomm_messaging/v1/crypto/base.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,26 +18,34 @@ class RecipData(NamedTuple):
1818
enc_cek: bytes
1919

2020

21-
class V1UnpackResult(NamedTuple):
21+
class V1CryptoUnpackResult(NamedTuple):
2222
"""Result of unpacking."""
2323

24-
message: bytes
24+
unpacked: bytes
2525
recip: str
2626
sender: Optional[str]
2727

2828

29+
class V1CryptoServiceError(Exception):
30+
"""Raised on errors in crypto service."""
31+
32+
2933
class V1CryptoService(ABC, Generic[P, S]):
3034
"""CryptoService interface for DIDComm v1."""
3135

3236
b64url = Base64UrlEncoder()
3337

3438
@abstractmethod
35-
def kid_to_public_key(self, kid: str) -> P:
39+
def v1_kid_to_public_key(self, kid: str) -> P:
3640
"""Get a public key from a kid.
3741
3842
In DIDComm v1, kids are the base58 encoded keys.
3943
"""
4044

45+
@abstractmethod
46+
def public_key_to_v1_kid(self, key: P) -> str:
47+
"""Return the DIDComm v1 kid representation for a key."""
48+
4149
@classmethod
4250
@abstractmethod
4351
def verification_method_to_public_key(cls, vm: VerificationMethod) -> P:
@@ -52,5 +60,5 @@ async def pack_message(
5260
@abstractmethod
5361
async def unpack_message(
5462
self, wrapper: JweEnvelope, recip_key: S, recip_data: RecipData
55-
) -> V1UnpackResult:
63+
) -> V1CryptoUnpackResult:
5664
"""Decode a message using DIDCvomm v1 'unpack' algorithm."""

didcomm_messaging/v1/crypto/nacl.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from didcomm_messaging.crypto.jwe import JweBuilder, JweEnvelope, JweRecipient
1111
from didcomm_messaging.multiformats import multibase, multicodec
1212

13-
from .base import V1CryptoService, V1UnpackResult, RecipData
13+
from .base import V1CryptoService, V1CryptoUnpackResult, RecipData
1414

1515
try:
1616
import nacl.bindings
@@ -60,7 +60,7 @@ def key(self) -> str:
6060
@property
6161
def kid(self) -> str:
6262
"""Get the key ID."""
63-
return self.key
63+
raise NotImplementedError()
6464

6565
@property
6666
def multikey(self) -> str:
@@ -69,22 +69,21 @@ def multikey(self) -> str:
6969
multicodec.wrap("ed25519-pub", base58.b58decode(self.key)), "base58btc"
7070
)
7171

72-
@property
73-
def key_bytes(self) -> bytes:
74-
"""Get the bytes of the key."""
75-
return self.value
76-
7772

7873
class NaclV1CryptoService(V1CryptoService[EdPublicKey, KeyPair]):
7974
"""V1 crypto service using pynacl."""
8075

81-
def kid_to_public_key(self, kid: str):
76+
def v1_kid_to_public_key(self, kid: str):
8277
"""Get a public key from a kid.
8378
8479
In DIDComm v1, kids are the base58 encoded keys.
8580
"""
8681
return EdPublicKey(base58.b58decode(kid))
8782

83+
def public_key_to_v1_kid(self, key: EdPublicKey) -> str:
84+
"""Convert a public key into a v1 kid representation."""
85+
return base58.b58encode(key.value).decode()
86+
8887
@classmethod
8988
def verification_method_to_public_key(cls, vm: VerificationMethod) -> EdPublicKey:
9089
"""Convert a verification method to a public key."""
@@ -120,19 +119,20 @@ async def pack_message(
120119
encrypted_key=enc_cek,
121120
header=OrderedDict(
122121
[
123-
("kid", target_vk.kid),
122+
("kid", self.public_key_to_v1_kid(target_vk)),
124123
("sender", self.b64url.encode(enc_sender)),
125124
("iv", self.b64url.encode(nonce)),
126125
]
127126
),
128127
)
129128
)
130129
else:
131-
enc_sender = None
132-
nonce = None
133130
enc_cek = nacl.bindings.crypto_box_seal(cek, target_xk)
134131
builder.add_recipient(
135-
JweRecipient(encrypted_key=enc_cek, header={"kid": target_vk.kid})
132+
JweRecipient(
133+
encrypted_key=enc_cek,
134+
header={"kid": self.public_key_to_v1_kid(target_vk)},
135+
)
136136
)
137137

138138
builder.set_protected(
@@ -180,15 +180,15 @@ def _extract_payload_key(self, recip_key: KeyPair, recip_data: RecipData):
180180

181181
async def unpack_message(
182182
self, wrapper: JweEnvelope, recip_key: KeyPair, recip_data: RecipData
183-
) -> V1UnpackResult:
183+
) -> V1CryptoUnpackResult:
184184
"""Decode a message using DIDCvomm v1 'unpack' algorithm."""
185185
cek, sender_vk = self._extract_payload_key(recip_key, recip_data)
186186

187187
payload_bin = wrapper.ciphertext + wrapper.tag
188188
message = nacl.bindings.crypto_aead_chacha20poly1305_ietf_decrypt(
189189
payload_bin, wrapper.protected_b64, wrapper.iv, cek
190190
)
191-
return V1UnpackResult(message, recip_key.kid, sender_vk)
191+
return V1CryptoUnpackResult(message, recip_key.kid, sender_vk)
192192

193193

194194
class InMemSecretsManager(SecretsManager[KeyPair]):
@@ -206,7 +206,7 @@ def _create_keypair(self, seed: Optional[bytes] = None) -> Tuple[bytes, bytes]:
206206
"""Create a keypair."""
207207
if seed:
208208
if not isinstance(seed, bytes):
209-
raise ValueError("Seed value is not a string or bytes")
209+
raise ValueError("Seed value is not bytes")
210210
if len(seed) != 32:
211211
raise ValueError("Seed value must be 32 bytes in length")
212212
else:

didcomm_messaging/v1/messaging.py

Lines changed: 15 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,14 @@
44
import json
55
from typing import Generic, Optional, Sequence, Union
66

7-
import base58
87
from pydantic import AnyUrl
9-
from pydid import VerificationMethod
8+
from pydid import DIDDocument, VerificationMethod
109
from pydid.service import DIDCommV1Service
1110

1211
from didcomm_messaging.crypto import P, S, SecretsManager
12+
from didcomm_messaging.resolver import DIDResolver
1313
from didcomm_messaging.v1.crypto.base import V1CryptoService
1414
from didcomm_messaging.v1.packaging import V1PackagingService
15-
from didcomm_messaging.resolver import DIDResolver
1615

1716

1817
class V1DIDCommMessagingError(Exception):
@@ -32,7 +31,7 @@ class V1UnpackResult:
3231
"""Result of unpacking a message."""
3332

3433
unpacked: bytes
35-
encrytped: bool
34+
encrypted: bool
3635
authenticated: bool
3736
recipient_kid: str
3837
sender_kid: Optional[str] = None
@@ -58,6 +57,14 @@ class Target:
5857
class V1DIDCommMessagingService(Generic[P, S]):
5958
"""Main entrypoint for DIDComm Messaging."""
6059

60+
def vm_to_v1_kid(self, crypto: V1CryptoService, doc: DIDDocument, ref: str) -> str:
61+
"""Convert a verification method ref to a DIDComm v1 kid."""
62+
return crypto.public_key_to_v1_kid(
63+
crypto.verification_method_to_public_key(
64+
doc.dereference_as(VerificationMethod, ref)
65+
)
66+
)
67+
6168
async def did_to_target(
6269
self, crypto: V1CryptoService[P, S], resolver: DIDResolver, did: str
6370
) -> Target:
@@ -73,19 +80,10 @@ async def did_to_target(
7380
target = services[0]
7481

7582
recipient_keys = [
76-
base58.b58encode(
77-
crypto.verification_method_to_public_key(
78-
doc.dereference_as(VerificationMethod, recip)
79-
).key_bytes
80-
).decode()
81-
for recip in target.recipient_keys
83+
self.vm_to_v1_kid(crypto, doc, recip) for recip in target.recipient_keys
8284
]
8385
routing_keys = [
84-
base58.b58encode(
85-
crypto.verification_method_to_public_key(
86-
doc.dereference_as(VerificationMethod, routing_key)
87-
).key_bytes
88-
).decode()
86+
self.vm_to_v1_kid(crypto, doc, routing_key)
8987
for routing_key in target.routing_keys
9088
]
9189
endpoint = target.service_endpoint
@@ -113,12 +111,7 @@ async def from_did_to_kid(
113111
target = services[0]
114112

115113
recipient_keys = [
116-
base58.b58encode(
117-
crypto.verification_method_to_public_key(
118-
doc.dereference_as(VerificationMethod, recip)
119-
).key_bytes
120-
).decode()
121-
for recip in target.recipient_keys
114+
self.vm_to_v1_kid(crypto, doc, recip) for recip in target.recipient_keys
122115
]
123116
return recipient_keys[0]
124117

@@ -211,7 +204,7 @@ async def unpack(
211204
unpacked, recip, sender = await packaging.unpack(crypto, secrets, encoded_message)
212205
return V1UnpackResult(
213206
unpacked,
214-
encrytped=bool(recip),
207+
encrypted=bool(recip),
215208
authenticated=bool(sender),
216209
recipient_kid=recip,
217210
sender_kid=sender,

0 commit comments

Comments
 (0)