python3-olm 3.2.18__cp310-cp310-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
olm/pk.py ADDED
@@ -0,0 +1,453 @@
1
+ # -*- coding: utf-8 -*-
2
+ # libolm python bindings
3
+ # Copyright © 2018 Damir Jelić <poljar@termina.org.uk>
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """libolm PK module.
17
+
18
+ This module contains bindings to the PK part of the Olm library.
19
+ It contains two classes PkDecryption and PkEncryption that are used to
20
+ establish an encrypted communication channel using public key encryption,
21
+ as well as a class PkSigning that is used to sign a message.
22
+
23
+ Examples:
24
+ >>> decryption = PkDecryption()
25
+ >>> encryption = PkEncryption(decryption.public_key)
26
+ >>> plaintext = "It's a secret to everybody."
27
+ >>> message = encryption.encrypt(plaintext)
28
+ >>> decrypted_plaintext = decryption.decrypt(message)
29
+ >>> seed = PkSigning.generate_seed()
30
+ >>> signing = PkSigning(seed)
31
+ >>> signature = signing.sign(plaintext)
32
+ >>> ed25519_verify(signing.public_key, plaintext, signature)
33
+
34
+ """
35
+
36
+ from builtins import super
37
+ from typing import AnyStr, Type
38
+
39
+ from _libolm import ffi, lib # type: ignore
40
+
41
+ from ._compat import URANDOM, to_bytearray, to_unicode_str
42
+ from ._finalize import track_for_finalization
43
+
44
+
45
+ class PkEncryptionError(Exception):
46
+ """libolm Pk encryption exception."""
47
+
48
+
49
+ class PkDecryptionError(Exception):
50
+ """libolm Pk decryption exception."""
51
+
52
+
53
+ class PkSigningError(Exception):
54
+ """libolm Pk signing exception."""
55
+
56
+
57
+ def _clear_pk_encryption(pk_struct):
58
+ lib.olm_clear_pk_encryption(pk_struct)
59
+
60
+
61
+ class PkMessage(object):
62
+ """A PK encrypted message."""
63
+
64
+ def __init__(self, ephemeral_key, mac, ciphertext):
65
+ # type: (str, str, str) -> None
66
+ """Create a new PK encrypted message.
67
+
68
+ Args:
69
+ ephemeral_key(str): the public part of the ephemeral key
70
+ used (together with the recipient's key) to generate a symmetric
71
+ encryption key.
72
+ mac(str): Message Authentication Code of the encrypted message
73
+ ciphertext(str): The cipher text of the encrypted message
74
+ """
75
+ self.ephemeral_key = ephemeral_key
76
+ self.mac = mac
77
+ self.ciphertext = ciphertext
78
+
79
+
80
+ class PkEncryption(object):
81
+ """PkEncryption class.
82
+
83
+ Represents the decryption part of a PK encrypted channel.
84
+ """
85
+
86
+ def __init__(self, recipient_key):
87
+ # type: (AnyStr) -> None
88
+ """Create a new PK encryption object.
89
+
90
+ Args:
91
+ recipient_key(str): a public key that will be used for encryption
92
+ """
93
+ if not recipient_key:
94
+ raise ValueError("Recipient key can't be empty")
95
+
96
+ self._buf = ffi.new("char[]", lib.olm_pk_encryption_size())
97
+ self._pk_encryption = lib.olm_pk_encryption(self._buf)
98
+ track_for_finalization(self, self._pk_encryption, _clear_pk_encryption)
99
+
100
+ byte_key = to_bytearray(recipient_key)
101
+ lib.olm_pk_encryption_set_recipient_key(
102
+ self._pk_encryption,
103
+ ffi.from_buffer(byte_key),
104
+ len(byte_key)
105
+ )
106
+
107
+ # clear out copies of the key
108
+ if byte_key is not recipient_key: # pragma: no cover
109
+ for i in range(0, len(byte_key)):
110
+ byte_key[i] = 0
111
+
112
+ def _check_error(self, ret): # pragma: no cover
113
+ # type: (int) -> None
114
+ if ret != lib.olm_error():
115
+ return
116
+
117
+ last_error = ffi.string(
118
+ lib.olm_pk_encryption_last_error(self._pk_encryption)
119
+ ).decode()
120
+
121
+ raise PkEncryptionError(last_error)
122
+
123
+ def encrypt(self, plaintext):
124
+ # type: (AnyStr) -> PkMessage
125
+ """Encrypt a message.
126
+
127
+ Returns the encrypted PkMessage.
128
+
129
+ Args:
130
+ plaintext(str): A string that will be encrypted using the
131
+ PkEncryption object.
132
+ """
133
+ byte_plaintext = to_bytearray(plaintext)
134
+
135
+ r_length = lib.olm_pk_encrypt_random_length(self._pk_encryption)
136
+ random = URANDOM(r_length)
137
+ random_buffer = ffi.new("char[]", random)
138
+
139
+ ciphertext_length = lib.olm_pk_ciphertext_length(
140
+ self._pk_encryption, len(byte_plaintext)
141
+ )
142
+ ciphertext = ffi.new("char[]", ciphertext_length)
143
+
144
+ mac_length = lib.olm_pk_mac_length(self._pk_encryption)
145
+ mac = ffi.new("char[]", mac_length)
146
+
147
+ ephemeral_key_size = lib.olm_pk_key_length()
148
+ ephemeral_key = ffi.new("char[]", ephemeral_key_size)
149
+
150
+ ret = lib.olm_pk_encrypt(
151
+ self._pk_encryption,
152
+ ffi.from_buffer(byte_plaintext), len(byte_plaintext),
153
+ ciphertext, ciphertext_length,
154
+ mac, mac_length,
155
+ ephemeral_key, ephemeral_key_size,
156
+ random_buffer, r_length
157
+ )
158
+
159
+ try:
160
+ self._check_error(ret)
161
+ finally: # pragma: no cover
162
+ # clear out copies of plaintext
163
+ if byte_plaintext is not plaintext:
164
+ for i in range(0, len(byte_plaintext)):
165
+ byte_plaintext[i] = 0
166
+
167
+ message = PkMessage(
168
+ ffi.unpack(ephemeral_key, ephemeral_key_size).decode(),
169
+ ffi.unpack(mac, mac_length).decode(),
170
+ ffi.unpack(ciphertext, ciphertext_length).decode(),
171
+ )
172
+ return message
173
+
174
+
175
+ def _clear_pk_decryption(pk_struct):
176
+ lib.olm_clear_pk_decryption(pk_struct)
177
+
178
+
179
+ class PkDecryption(object):
180
+ """PkDecryption class.
181
+
182
+ Represents the decryption part of a PK encrypted channel.
183
+
184
+ Attributes:
185
+ public_key (str): The public key of the PkDecryption object, can be
186
+ shared and used to create a PkEncryption object.
187
+
188
+ """
189
+
190
+ def __new__(cls):
191
+ # type: (Type[PkDecryption]) -> PkDecryption
192
+ obj = super().__new__(cls)
193
+ obj._buf = ffi.new("char[]", lib.olm_pk_decryption_size())
194
+ obj._pk_decryption = lib.olm_pk_decryption(obj._buf)
195
+ obj.public_key = None
196
+ track_for_finalization(obj, obj._pk_decryption, _clear_pk_decryption)
197
+ return obj
198
+
199
+ def __init__(self):
200
+ if False: # pragma: no cover
201
+ self._pk_decryption = self._pk_decryption # type: ffi.cdata
202
+
203
+ random_length = lib.olm_pk_private_key_length()
204
+ random = URANDOM(random_length)
205
+ random_buffer = ffi.new("char[]", random)
206
+
207
+ key_length = lib.olm_pk_key_length()
208
+ key_buffer = ffi.new("char[]", key_length)
209
+
210
+ ret = lib.olm_pk_key_from_private(
211
+ self._pk_decryption,
212
+ key_buffer, key_length,
213
+ random_buffer, random_length
214
+ )
215
+ self._check_error(ret)
216
+ self.public_key: str = ffi.unpack(
217
+ key_buffer,
218
+ key_length
219
+ ).decode()
220
+
221
+ def _check_error(self, ret):
222
+ # type: (int) -> None
223
+ if ret != lib.olm_error():
224
+ return
225
+
226
+ last_error = ffi.string(
227
+ lib.olm_pk_decryption_last_error(self._pk_decryption)
228
+ ).decode()
229
+
230
+ raise PkDecryptionError(last_error)
231
+
232
+ def pickle(self, passphrase=""):
233
+ # type: (str) -> bytes
234
+ """Store a PkDecryption object.
235
+
236
+ Stores a PkDecryption object as a base64 string. Encrypts the object
237
+ using the supplied passphrase. Returns a byte object containing the
238
+ base64 encoded string of the pickled session.
239
+
240
+ Args:
241
+ passphrase(str, optional): The passphrase to be used to encrypt
242
+ the object.
243
+ """
244
+ byte_key = to_bytearray(passphrase)
245
+
246
+ pickle_length = lib.olm_pickle_pk_decryption_length(
247
+ self._pk_decryption
248
+ )
249
+ pickle_buffer = ffi.new("char[]", pickle_length)
250
+
251
+ ret = lib.olm_pickle_pk_decryption(
252
+ self._pk_decryption,
253
+ ffi.from_buffer(byte_key), len(byte_key),
254
+ pickle_buffer, pickle_length
255
+ )
256
+ try:
257
+ self._check_error(ret)
258
+ finally:
259
+ # zero out copies of the passphrase
260
+ for i in range(0, len(byte_key)):
261
+ byte_key[i] = 0
262
+
263
+ return ffi.unpack(pickle_buffer, pickle_length)
264
+
265
+ @classmethod
266
+ def from_pickle(cls, pickle, passphrase=""):
267
+ # type: (bytes, str) -> PkDecryption
268
+ """Restore a previously stored PkDecryption object.
269
+
270
+ Creates a PkDecryption object from a pickled base64 string. Decrypts
271
+ the pickled object using the supplied passphrase.
272
+ Raises PkDecryptionError on failure. If the passphrase
273
+ doesn't match the one used to encrypt the session then the error
274
+ message for the exception will be "BAD_ACCOUNT_KEY". If the base64
275
+ couldn't be decoded then the error message will be "INVALID_BASE64".
276
+
277
+ Args:
278
+ pickle(bytes): Base64 encoded byte string containing the pickled
279
+ PkDecryption object
280
+ passphrase(str, optional): The passphrase used to encrypt the
281
+ object
282
+ """
283
+ if not pickle:
284
+ raise ValueError("Pickle can't be empty")
285
+
286
+ byte_key = to_bytearray(passphrase)
287
+ pickle_buffer = ffi.new("char[]", pickle)
288
+
289
+ pubkey_length = lib.olm_pk_key_length()
290
+ pubkey_buffer = ffi.new("char[]", pubkey_length)
291
+
292
+ obj = cls.__new__(cls)
293
+
294
+ ret = lib.olm_unpickle_pk_decryption(
295
+ obj._pk_decryption,
296
+ ffi.from_buffer(byte_key), len(byte_key),
297
+ pickle_buffer, len(pickle),
298
+ pubkey_buffer, pubkey_length)
299
+
300
+ try:
301
+ obj._check_error(ret)
302
+ finally:
303
+ for i in range(0, len(byte_key)):
304
+ byte_key[i] = 0
305
+
306
+ obj.public_key = ffi.unpack(
307
+ pubkey_buffer,
308
+ pubkey_length
309
+ ).decode()
310
+
311
+ return obj
312
+
313
+ def decrypt(self, message, unicode_errors="replace"):
314
+ # type: (PkMessage, str) -> str
315
+ """Decrypt a previously encrypted Pk message.
316
+
317
+ Returns the decrypted plaintext.
318
+ Raises PkDecryptionError on failure.
319
+
320
+ Args:
321
+ message(PkMessage): the pk message to decrypt.
322
+ unicode_errors(str, optional): The error handling scheme to use for
323
+ unicode decoding errors. The default is "replace" meaning that
324
+ the character that was unable to decode will be replaced with
325
+ the unicode replacement character (U+FFFD). Other possible
326
+ values are "strict", "ignore" and "xmlcharrefreplace" as well
327
+ as any other name registered with codecs.register_error that
328
+ can handle UnicodeEncodeErrors.
329
+ """
330
+ ephemeral_key = to_bytearray(message.ephemeral_key)
331
+ ephemeral_key_size = len(ephemeral_key)
332
+
333
+ mac = to_bytearray(message.mac)
334
+ mac_length = len(mac)
335
+
336
+ ciphertext = to_bytearray(message.ciphertext)
337
+ ciphertext_length = len(ciphertext)
338
+
339
+ max_plaintext_length = lib.olm_pk_max_plaintext_length(
340
+ self._pk_decryption,
341
+ ciphertext_length
342
+ )
343
+ plaintext_buffer = ffi.new("char[]", max_plaintext_length)
344
+
345
+ ret = lib.olm_pk_decrypt(
346
+ self._pk_decryption,
347
+ ffi.from_buffer(ephemeral_key), ephemeral_key_size,
348
+ ffi.from_buffer(mac), mac_length,
349
+ ffi.from_buffer(ciphertext), ciphertext_length,
350
+ plaintext_buffer, max_plaintext_length)
351
+ self._check_error(ret)
352
+
353
+ plaintext = (ffi.unpack(
354
+ plaintext_buffer,
355
+ ret
356
+ ))
357
+
358
+ # clear out copies of the plaintext
359
+ lib.memset(plaintext_buffer, 0, max_plaintext_length)
360
+
361
+ return to_unicode_str(plaintext, errors=unicode_errors)
362
+
363
+
364
+ def _clear_pk_signing(pk_struct):
365
+ lib.olm_clear_pk_signing(pk_struct)
366
+
367
+
368
+ class PkSigning(object):
369
+ """PkSigning class.
370
+
371
+ Signs messages using public key cryptography.
372
+
373
+ Attributes:
374
+ public_key (str): The public key of the PkSigning object, can be
375
+ shared and used to verify using Utility.ed25519_verify.
376
+
377
+ """
378
+
379
+ def __init__(self, seed):
380
+ # type: (bytes) -> None
381
+ """Create a new signing object.
382
+
383
+ Args:
384
+ seed(bytes): the seed to use as the private key for signing. The
385
+ seed must have the same length as the seeds generated by
386
+ PkSigning.generate_seed().
387
+ """
388
+ if not seed:
389
+ raise ValueError("seed can't be empty")
390
+
391
+ self._buf = ffi.new("char[]", lib.olm_pk_signing_size())
392
+ self._pk_signing = lib.olm_pk_signing(self._buf)
393
+ track_for_finalization(self, self._pk_signing, _clear_pk_signing)
394
+
395
+ seed_buffer = ffi.new("char[]", seed)
396
+
397
+ pubkey_length = lib.olm_pk_signing_public_key_length()
398
+ pubkey_buffer = ffi.new("char[]", pubkey_length)
399
+
400
+ ret = lib.olm_pk_signing_key_from_seed(
401
+ self._pk_signing,
402
+ pubkey_buffer, pubkey_length,
403
+ seed_buffer, len(seed)
404
+ )
405
+
406
+ # zero out copies of the seed
407
+ lib.memset(seed_buffer, 0, len(seed))
408
+
409
+ self._check_error(ret)
410
+
411
+ self.public_key = ffi.unpack(pubkey_buffer, pubkey_length).decode()
412
+
413
+ def _check_error(self, ret):
414
+ # type: (int) -> None
415
+ if ret != lib.olm_error():
416
+ return
417
+
418
+ last_error = ffi.string(lib.olm_pk_signing_last_error(self._pk_signing)).decode()
419
+
420
+ raise PkSigningError(last_error)
421
+
422
+ @classmethod
423
+ def generate_seed(cls):
424
+ # type: () -> bytes
425
+ """Generate a random seed.
426
+ """
427
+ random_length = lib.olm_pk_signing_seed_length()
428
+ random = URANDOM(random_length)
429
+
430
+ return random
431
+
432
+ def sign(self, message):
433
+ # type: (AnyStr) -> str
434
+ """Sign a message
435
+
436
+ Returns the signature.
437
+ Raises PkSigningError on failure.
438
+
439
+ Args:
440
+ message(str): the message to sign.
441
+ """
442
+ bytes_message = to_bytearray(message)
443
+
444
+ signature_length = lib.olm_pk_signature_length()
445
+ signature_buffer = ffi.new("char[]", signature_length)
446
+
447
+ ret = lib.olm_pk_sign(
448
+ self._pk_signing,
449
+ ffi.from_buffer(bytes_message), len(bytes_message),
450
+ signature_buffer, signature_length)
451
+ self._check_error(ret)
452
+
453
+ return ffi.unpack(signature_buffer, signature_length).decode()
olm/py.typed ADDED
File without changes