summaryrefslogtreecommitdiffstats
path: root/ffi/lang/python/tests/test_packet_parser.py
blob: e50a58f5a624711723602aee980b7f621d36566f (plain)
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
from enum import Enum
from sequoia.core import Context, NetworkPolicy
from sequoia.openpgp import Tag, PacketParser

pgp = "../../../openpgp/tests/data/messages/encrypted-aes128-password-123456789.gpg"
plain = "../../../openpgp/tests/data/messages/a-cypherpunks-manifesto.txt"

def test_decryption():
    ctx = Context(network_policy=NetworkPolicy.Offline,
                  ephemeral=True)

    class State(Enum):
        # XXX: In Python 3.6, we can use enum.auto() to assign values.
        # But we want to support Debian 9, which uses Python 3.5, as
        # long as it is Debian stable.
        Start = 1
        Decrypted = 2
        Deciphered = 3
        Done = 4

    state = State.Start
    algo, key = None, None
    ppr = PacketParser.open(ctx, pgp)
    while True:
        pp = ppr.packet_parser()
        if not pp:
            break

        packet = pp.packet
        tag = packet.tag
        print(state, pp.recursion_depth, packet)

        if state == State.Start:
            assert pp.recursion_depth == 0
            if tag == Tag.SKESK:
                algo, key = packet.match().decrypt(b"123456789")
                state = State.Decrypted
        elif state == State.Decrypted:
            assert pp.recursion_depth == 0
            if tag == Tag.SEIP:
                pp.decrypt(algo, key)
                state = State.Deciphered
        elif state == State.Deciphered:
            assert pp.recursion_depth == 1
            if tag == Tag.Literal:
                body = pp.buffer_unread_content()
                assert body[:].decode() == open(plain).read()
                state = State.Done

        _, ppr = pp.recurse()

    assert ppr.eof().is_message()
    assert state == State.Done