summaryrefslogtreecommitdiffstats
path: root/ffi/lang/python/examples/decrypt.py
blob: 1f4109e13d8c6a1c7618167d0a093ffe038d0dd3 (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
import sys
import os
from getpass import getpass
from enum import Enum, auto
from sequoia.core import Context, NetworkPolicy
from sequoia.openpgp import Tag, PacketParser

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

class State(Enum):
    Start = auto()
    Decrypted = auto()
    Deciphered = auto()
    Done = auto()

state = State.Start
algo, key = None, None
pp = PacketParser.open(ctx, sys.argv[1])
while pp.has_packet:
    packet = pp.packet
    tag = packet.tag

    if state == State.Start:
        if tag == Tag.SKESK:
            passphrase = getpass("Enter passphrase to decrypt message: ")
            algo, key = packet.match().decrypt(passphrase.encode())
            state = State.Decrypted
        elif tag == Tag.PKESK:
            sys.stderr.write("Decryption using PKESK not yet supported.\n")
    elif state == State.Decrypted:
        if tag == Tag.SEIP:
            pp.decrypt(algo, key)
            state = State.Deciphered
    elif state == State.Deciphered:
        if tag == Tag.Literal:
            body = pp.buffer_unread_content()
            os.write(sys.stdout.fileno(), body)
            state = State.Done

    pp.recurse()
assert state == State.Done