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

Bastian Germann bage at linutronix.de
Sat Mar 4 11:28:56 CET 2023


Add a function to convert an ascii-armored OpenPGP key to its binary
representation.

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
@@ -5,6 +5,7 @@
 #
 # SPDX-License-Identifier: GPL-3.0-or-later
 
+import binascii
 import os
 
 from gpg import core
@@ -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
+            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)
+
 # pylint: disable=too-many-instance-attributes
 class OverallStatus:
 
-- 
2.39.2



More information about the elbe-devel mailing list