File: rnp.py

package info (click to toggle)
py-rnp 0.1.0%2Bgit20221014.01b7129-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 424 kB
  • sloc: python: 3,062; sh: 8; makefile: 4
file content (513 lines) | stat: -rw-r--r-- 15,680 bytes parent folder | download
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
#!/usr/bin/env python

from collections.abc import Iterable

from ctypes import (
    pointer,
    c_bool,
    c_char_p,
    c_void_p,
    c_size_t,
    byref,
    c_char,
    addressof,
    py_object,
    cast,
    CFUNCTYPE,
    POINTER,
)
import json
from .lib import (
    _lib,
    _flags,
    _obj,
    _encode,
    _inp,
    PASS_PROVIDER,
    KEY_PROVIDER,
    RNP_LOAD_SAVE_PUBLIC_KEYS,
    RNP_LOAD_SAVE_SECRET_KEYS,
    RNP_LOAD_SAVE_PERMISSIVE,
    RNP_LOAD_SAVE_SINGLE,
)
from .output import Output
from .key import Key
from .op.sign import Sign
from .op.verify import Verify
from .op.encrypt import Encrypt


class Rnp:
    def __init__(self, pub_format="GPG", sec_format="GPG"):
        self._obj = c_void_p()
        _lib.rnp_ffi_create(
            byref(self._obj), pub_format.encode("ascii"), sec_format.encode("ascii")
        )

    def __del__(self):
        _lib.rnp_ffi_destroy(self._obj)

    def obj(self):
        return self._obj

    def load_keys(self, inp, fmt, public_keys=True, secret_keys=True):
        inp = _inp(inp)
        flags = Rnp._load_save_flags(public_keys, secret_keys)
        _lib.rnp_load_keys(self._obj, fmt.encode("ascii"), inp.obj(), flags)

    def unload_keys(self, public_keys=True, secret_keys=True):
        flags = Rnp._load_save_flags(public_keys, secret_keys)
        _lib.rnp_unload_keys(self._obj, flags)

    def save_keys(self, outp, fmt, public_keys=True, secret_keys=True):
        flags = Rnp._load_save_flags(public_keys, secret_keys)
        _lib.rnp_save_keys(self._obj, fmt.encode("ascii"), outp.obj(), flags)

    def import_keys(
        self, inp, public_keys=True, secret_keys=True, permissive=True, single=False
    ):
        inp = _inp(inp)
        try:
            jsn = None
            pjsn = pointer(c_char_p())
            flags = Rnp._import_key_flags(public_keys, secret_keys, permissive, single)
            _lib.rnp_import_keys(self._obj, inp.obj(), flags, pjsn)
            jsn = pjsn.contents
            return json.loads(jsn.value.decode("utf-8"))
        finally:
            _lib.rnp_buffer_destroy(jsn)

    def import_signatures(self, inp):
        inp = _inp(inp)
        try:
            jsn = None
            pjsn = pointer(c_char_p())
            _lib.rnp_import_signatures(self._obj, inp.obj(), 0, pjsn)
            jsn = pjsn.contents
            return json.loads(jsn.value.decode("utf-8"))
        finally:
            _lib.rnp_buffer_destroy(jsn)

    def public_key_count(self):
        count = c_size_t()
        _lib.rnp_get_public_key_count(self._obj, byref(count))
        return count.value

    def secret_key_count(self):
        count = c_size_t()
        _lib.rnp_get_secret_key_count(self._obj, byref(count))
        return count.value

    def _find_key(self, identifier_type, identifier):
        handle = c_void_p()
        _lib.rnp_locate_key(self._obj, identifier_type, identifier, byref(handle))
        if handle.value:
            return Key(handle)

    def find_key_by_id(self, keyid):
        return self._find_key("keyid".encode("ascii"), keyid.encode("ascii"))

    def find_key_by_userid(self, userid):
        return self._find_key("userid".encode("ascii"), userid.encode("utf-8"))

    def find_key_by_fingerprint(self, fpr):
        return self._find_key("fingerprint".encode("ascii"), fpr.encode("ascii"))

    def userids(self):
        return self._identifiers("userid")

    def keyids(self):
        return self._identifiers("keyid")

    def fingerprints(self):
        return self._identifiers("fingerprint")

    def grips(self):
        return self._identifiers("grip")

    def _identifiers(self, typ):
        it = c_void_p()
        try:
            _lib.rnp_identifier_iterator_create(
                self._obj, byref(it), typ.encode("ascii")
            )
            while True:
                identifier = c_char_p()
                _lib.rnp_identifier_iterator_next(it, byref(identifier))
                if identifier.value:
                    # pylint: disable=E1101
                    yield identifier.value.decode("utf-8")
                else:
                    break
        finally:
            _lib.rnp_identifier_iterator_destroy(it)

    def generate_key(self, description):
        try:
            presults = c_char_p()
            jsn = json.dumps(description)
            _lib.rnp_generate_key_json(self._obj, jsn.encode("utf-8"), byref(presults))
            # pylint: disable=E1101
            results = json.loads(presults.value.decode("utf-8"))
            for entry in results:
                results[entry] = self._find_key(
                    next(iter(results[entry].keys())).encode("ascii"),
                    next(iter(results[entry].values())).encode("ascii"),
                )
            return results
        finally:
            _lib.rnp_buffer_destroy(presults)

    def generate_rsa(self, userid, password, bits, subbits=0):
        pkey = c_void_p()
        _lib.rnp_generate_key_rsa(
            self._obj,
            bits,
            subbits,
            userid.encode("utf-8"),
            _encode(password),
            byref(pkey),
        )
        if pkey.value:
            return Key(pkey)

    def generate_dsa_elgamal(self, userid, password, bits, subbits=0):
        pkey = c_void_p()
        _lib.rnp_generate_key_dsa_eg(
            self._obj,
            bits,
            subbits,
            userid.encode("utf-8"),
            _encode(password),
            byref(pkey),
        )
        if pkey.value:
            return Key(pkey)

    def generate_ecdsa_ecdh(self, userid, password, curve):
        pkey = c_void_p()
        _lib.rnp_generate_key_ec(
            self._obj,
            curve.encode("ascii"),
            userid.encode("utf-8"),
            _encode(password),
            byref(pkey),
        )
        if pkey.value:
            return Key(pkey)

    def generate_eddsa_25519(self, userid, password):
        pkey = c_void_p()
        _lib.rnp_generate_key_25519(
            self._obj, userid.encode("utf-8"), _encode(password), byref(pkey)
        )
        if pkey.value:
            return Key(pkey)

    def generate_sm2(self, userid, password):
        pkey = c_void_p()
        _lib.rnp_generate_key_sm2(
            self._obj, userid.encode("utf-8"), _encode(password), byref(pkey)
        )
        if pkey.value:
            return Key(pkey)

    def generate(
        self, userid, password, typ, bits, curve, subtyp=None, subbits=0, subcurve=None
    ):
        pkey = c_void_p()
        _lib.rnp_generate_key_ex(
            self._obj,
            typ.encode("ascii"),
            _encode(subtyp),
            bits,
            subbits,
            _encode(curve),
            _encode(subcurve),
            userid.encode("utf-8"),
            _encode(password),
            byref(pkey),
        )
        if pkey.value:
            return Key(pkey)

    def export_autocrypt(self, userid, primary, subkey=None, outp=None):
        with Output.default(outp) as outp:
            _lib.rnp_key_export_autocrypt(
                primary.obj(), _obj(subkey), _encode(userid), outp.obj(), 0
            )
            return outp.default_output()

    def sign(
        self,
        signers,
        inp,
        armored=None,
        hashalg=None,
        compression=None,
        creation_time=None,
        lifetime=None,
        outp=None,
    ):
        with Output.default(outp) as outp:
            op = Sign.start(self, inp, outp)
            self._do_sign(
                op, signers, armored, hashalg, compression, creation_time, lifetime
            )
            return outp.default_output()

    def sign_cleartext(
        self,
        signers,
        inp,
        hashalg=None,
        compression=None,
        creation_time=None,
        lifetime=None,
        outp=None,
    ):
        with Output.default(outp) as outp:
            op = Sign.start_cleartext(self, inp, outp)
            self._do_sign(
                op, signers, None, hashalg, compression, creation_time, lifetime
            )
            return outp.default_output()

    def sign_detached(
        self,
        signers,
        inp,
        armored=None,
        hashalg=None,
        compression=None,
        creation_time=None,
        lifetime=None,
        outp=None,
    ):
        with Output.default(outp) as outp:
            op = Sign.start_detached(self, inp, outp)
            self._do_sign(
                op, signers, armored, hashalg, compression, creation_time, lifetime
            )
            return outp.default_output()

    def verify(self, inp, outp=None):
        op = Verify.start(self, inp, outp)
        op.finish()
        return op

    def verify_detached(self, inpdata, inpsig):
        op = Verify.start_detached(self, inpdata, inpsig)
        op.finish()
        return op

    def encrypt(
        self,
        inp,
        recipients,
        armored=None,
        compression=None,
        cipher=None,
        aead=None,
        aead_bits=None,
        outp=None,
    ):
        with Output.default(outp) as outp:
            op = Encrypt.start(self, inp, outp)
            self._do_encrypt(
                op,
                recipients,
                armored=armored,
                compression=compression,
                cipher=cipher,
                aead=aead,
                aead_bits=aead_bits,
            )
            return outp.default_output()

    def encrypt_and_sign(
        self,
        inp,
        recipients,
        signers,
        armored=None,
        compression=None,
        cipher=None,
        aead=None,
        aead_bits=None,
        hashalg=None,
        creation_time=None,
        lifetime=None,
        outp=None,
    ):
        with Output.default(outp) as outp:
            op = Encrypt.start(self, inp, outp)
            if hashalg is not None:
                op.hashalg = hashalg
            if creation_time is not None:
                op.creation_time = creation_time
            if lifetime is not None:
                op.lifetime = lifetime

            signers = [] if signers is None else signers
            signers = [signers] if isinstance(signers, Key) else signers
            for signer in signers:
                op.add_signature(signer)

            self._do_encrypt(
                op,
                recipients=recipients,
                armored=armored,
                compression=compression,
                cipher=cipher,
                aead=aead,
                aead_bits=aead_bits,
            )
            return outp.default_output()

    def symmetric_encrypt(
        self,
        inp,
        passwords,
        armored=None,
        compression=None,
        cipher=None,
        aead=None,
        aead_bits=None,
        s2k_hashalg=None,
        s2k_iterations=None,
        s2k_cipher=None,
        outp=None,
    ):
        with Output.default(outp) as outp:
            op = Encrypt.start(self, inp, outp)
            passwords = [] if passwords is None else passwords
            passwords = (
                [passwords]
                if isinstance(passwords, (str, bytes, bytearray))
                else passwords
            )
            for password in passwords:
                op.add_password(password, s2k_hashalg, s2k_iterations, s2k_cipher)

            self._do_encrypt(
                op,
                recipients=None,
                armored=armored,
                compression=compression,
                cipher=cipher,
                aead=aead,
                aead_bits=aead_bits,
            )
            return outp.default_output()

    @staticmethod
    def _do_encrypt(op, recipients, armored, compression, cipher, aead, aead_bits):
        if armored is not None:
            op.armored = armored
        if compression is not None:
            op.compression = compression
        if cipher is not None:
            op.cipher = cipher
        if aead is not None:
            op.aead = aead
        if aead_bits is not None:
            op.aead_bits = aead_bits
        recipients = [] if recipients is None else recipients
        recipients = [recipients] if isinstance(recipients, Key) else recipients
        for recipient in recipients:
            op.add_recipient(recipient)

        op.finish()

    @staticmethod
    def _do_sign(op, signers, armored, hashalg, compression, creation_time, lifetime):
        signers = (signers,) if not isinstance(signers, Iterable) else signers
        for signer in signers:
            op.add_signer(signer)
        if armored is not None:
            op.armored = armored
        if hashalg is not None:
            op.hashalg = hashalg
        if compression is not None:
            op.compression = compression
        if creation_time is not None:
            op.creation_time = creation_time
        if lifetime is not None:
            op.lifetime = lifetime
        op.finish()

    def decrypt(self, inp, outp=None):
        inp = _inp(inp)
        with Output.default(outp) as outp:
            _lib.rnp_decrypt(self._obj, inp.obj(), outp.obj())
            return outp.default_output()

    def set_password_provider(self, provider):
        if provider is None:
            _lib.rnp_ffi_set_pass_provider(self._obj, cast(None, PASS_PROVIDER), None)
        else:
            self.pass_provider = py_object(provider)
            _lib.rnp_ffi_set_pass_provider(
                self._obj, Rnp.PASS_PROVIDER_PROXY, byref(self.pass_provider)
            )

    @staticmethod
    @CFUNCTYPE(
        c_bool, c_void_p, c_void_p, c_void_p, c_char_p, POINTER(c_char), c_size_t
    )
    def PASS_PROVIDER_PROXY(_rnp, app_ctx, pkey, reason, buf, buf_len):
        password = cast(app_ctx, POINTER(py_object)).contents.value
        if callable(password):
            key = Key(c_void_p(pkey), False)
            password = password(key, reason)

        if password is not None:
            if isinstance(password, str):
                password = password.encode("utf-8")

            if len(password) >= buf_len:
                return False

            buf = (c_char * buf_len).from_address(addressof(buf.contents))
            buf[: len(password)] = password[: len(password)]
            return True

        return False

    def set_key_provider(self, provider):
        if provider is None:
            _lib.rnp_ffi_set_key_provider(self._obj, cast(None, KEY_PROVIDER), None)
        else:
            self.key_provider = py_object([provider, self])
            _lib.rnp_ffi_set_key_provider(
                self._obj, Rnp.KEY_PROVIDER_PROXY, byref(self.key_provider)
            )

    @staticmethod
    @CFUNCTYPE(None, c_void_p, c_void_p, c_char_p, c_char_p, c_bool)
    def KEY_PROVIDER_PROXY(_rnp, app_ctx, identifier_type, identifier, is_secret):
        ctx = cast(app_ctx, POINTER(py_object)).contents.value
        identifier_type = identifier_type.decode("ascii")
        identifier = identifier.decode("utf-8")
        return ctx[0](ctx[1], identifier_type, identifier, is_secret)

    @staticmethod
    def _load_save_flags(public_keys, secret_keys):
        return _flags(
            [
                (public_keys, RNP_LOAD_SAVE_PUBLIC_KEYS),
                (secret_keys, RNP_LOAD_SAVE_SECRET_KEYS),
            ]
        )

    @staticmethod
    def _import_key_flags(public_keys, secret_keys, permissive, single):
        return _flags(
            [
                (public_keys, RNP_LOAD_SAVE_PUBLIC_KEYS),
                (secret_keys, RNP_LOAD_SAVE_SECRET_KEYS),
                (permissive, RNP_LOAD_SAVE_PERMISSIVE),
                (single, RNP_LOAD_SAVE_SINGLE),
            ]
        )