Skip to content

Commit f3e6c69

Browse files
committed
add crypto/olm_device.py and sign json
1 parent 65321d3 commit f3e6c69

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

matrix_client/crypto/olm_device.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import logging
2+
3+
import olm
4+
from canonicaljson import encode_canonical_json
5+
6+
from matrix_client.checks import check_user_id
7+
8+
logger = logging.getLogger(__name__)
9+
10+
11+
class OlmDevice(object):
12+
"""Manages the Olm cryptographic functions.
13+
14+
Has a unique Olm account which holds identity keys.
15+
16+
Args:
17+
api (MatrixHttpApi): The api object used to make requests.
18+
user_id (str): Matrix user ID. Must match the one used when logging in.
19+
device_id (str): Must match the one used when logging in.
20+
"""
21+
22+
def __init__(self, api, user_id, device_id):
23+
self.api = api
24+
check_user_id(user_id)
25+
self.user_id = user_id
26+
self.device_id = device_id
27+
self.olm_account = olm.Account()
28+
logger.info('Initialised Olm Device.')
29+
30+
def sign_json(self, json):
31+
"""Signs a JSON object.
32+
33+
NOTE: The object is modified in-place and the return value can be ignored.
34+
35+
As specified, this is done by encoding the JSON object without ``signatures`` or
36+
keys grouped as ``unsigned``, using canonical encoding.
37+
38+
Args:
39+
json (dict): The JSON object to sign.
40+
41+
Returns:
42+
The same JSON object, with a ``signatures`` key added. It is formatted as
43+
``"signatures": ed25519:<device_id>: <base64_signature>``.
44+
"""
45+
signatures = json.pop('signatures', {})
46+
unsigned = json.pop('unsigned', None)
47+
48+
signature_base64 = self.olm_account.sign(encode_canonical_json(json))
49+
50+
key_id = 'ed25519:{}'.format(self.device_id)
51+
signatures.setdefault(self.user_id, {})[key_id] = signature_base64
52+
53+
json['signatures'] = signatures
54+
if unsigned:
55+
json['unsigned'] = unsigned
56+
57+
return json

0 commit comments

Comments
 (0)