[elbe-devel] [PATCH 6/9] egpg: Implement unarmor_openpgp_keyring

John Ogness john.ogness at linutronix.de
Mon Mar 6 11:38:20 CET 2023


On 2023-03-04, Bastian Germann <bage at linutronix.de> wrote:
> Add a function to convert an ascii-armored OpenPGP key to its binary
> representation.

Generally speaking, this is a bad idea. When existing tools exist (which
they do), they should be used. More below...

> Signed-off-by: Bastian Germann <bage at linutronix.de>
> ---
>  elbepack/egpg.py | 32 ++++++++++++++++++++++++++++++++
>  1 file changed, 32 insertions(+)
>
> diff --git a/elbepack/egpg.py b/elbepack/egpg.py
> index 653d02d856..300a163311 100644
> --- a/elbepack/egpg.py
> +++ b/elbepack/egpg.py
> @@ -27,6 +28,37 @@ elbe_internal_key_param = """
>  </GnupgKeyParms>
>  """
>  
> +def unarmor_openpgp_keyring(armored):
> +    """
> +    Unarmors one ascii-armored (string) OpenPGP keyring.
> +    This does not involve gpg but is implemented in pure python.
> +    The first line has to be the armor header.
> +    Anything after the footer is ignored, and the CRC-24 is ignored
> +    because a key is checked by gpg on use anyway.
> +
> +    Returns a binary string (empty for invalid keys).
> +    """
> +    offset = -1
> +    end = -1
> +    lines = armored.splitlines()
> +    for i, line in enumerate(lines):
> +        stripped = line.strip()
> +        if not stripped:
> +            if offset >= 0:
> +                # only one empty line allowed
> +                break
> +            offset = i + 1
> +        elif stripped == '-----END PGP PUBLIC KEY BLOCK-----':
> +            # exclude the last line before the footer, which is CRC-24

Ignoring the CRC is a bad idea. If you are going to reinvent the wheel,
please make it complete.

> +            end = i - 1
> +            break
> +
> +    if offset < 2 or offset >= len(lines) or offset > end:
> +        return b""
> +
> +    base64_payload = "\n".join(lines[offset:end])
> +    return binascii.a2b_base64(base64_payload)

John


More information about the elbe-devel mailing list