diff libervia/backend/plugins/plugin_xep_0373.py @ 4346:62746042e6d9

plugin gre encrypter: implement GRE Encrypter: OpenPGP: rel 455
author Goffi <goffi@goffi.org>
date Mon, 13 Jan 2025 01:23:22 +0100
parents 111dce64dcb5
children
line wrap: on
line diff
--- a/libervia/backend/plugins/plugin_xep_0373.py	Mon Jan 13 01:23:22 2025 +0100
+++ b/libervia/backend/plugins/plugin_xep_0373.py	Mon Jan 13 01:23:22 2025 +0100
@@ -20,7 +20,6 @@
 import base64
 from datetime import datetime, timezone
 import enum
-import json
 import secrets
 import string
 from typing import Any, Dict, Iterable, List, Literal, Optional, Set, Tuple, cast
@@ -74,7 +73,6 @@
     "GPGSecretKey",
     "GPGProvider",
     "PublicKeyMetadata",
-    "gpg_provider",
     "TrustLevel",
 ]
 
@@ -103,6 +101,61 @@
 STR_KEY_PUBLIC_KEYS_METADATA = "/public-keys-metadata/{}"
 
 
+def crc24(data: bytes) -> int:
+    """Compute the CRC-24 checksum for the given data.
+
+    @param data: The binary data to compute the checksum for.
+    @return: The 24-bit CRC checksum.
+    """
+    crc = 0xB704CE
+    for byte in data:
+        crc ^= byte << 16
+        for _ in range(8):
+            crc <<= 1
+            if crc & 0x1000000:
+                crc ^= 0x1864CFB
+    return crc & 0xFFFFFF
+
+
+def binary_to_ascii_armor(
+    data: bytes,
+    armor_type: str = "MESSAGE",
+    headers: dict|None = None,
+    line_length: int = 76
+) -> str:
+    """Convert binary data to OpenPGP ASCII Armor format.
+
+    @param data: The binary data to encode.
+    @param armor_type: The type of armor (e.g., "MESSAGE", "PUBLIC KEY BLOCK").
+    @param headers: Optional dictionary of headers to include in the armor.
+    @param line_length: Maximum length of each line.
+    @return: The ASCII Armor encoded string.
+    """
+    encoded_data = base64.b64encode(data).decode('ascii')
+
+    encoded_lines = [
+        encoded_data[i:i+line_length] for i in range(0, len(encoded_data), line_length)
+    ]
+
+    checksum = crc24(data)
+    checksum_str = base64.b64encode(checksum.to_bytes(3, 'big')).decode('ascii')
+
+    header_lines = []
+    if headers:
+        for key, value in headers.items():
+            header_lines.append(f"{key}: {value}")
+
+    armor = []
+    armor.append(f"-----BEGIN PGP {armor_type}-----")
+    armor.extend(header_lines)
+    armor.append("")
+    armor.extend(encoded_lines)
+    armor.append(f"={checksum_str}")
+    armor.append(f"-----END PGP {armor_type}-----")
+
+    return '\n'.join(armor)
+
+
 class VerificationError(Exception):
     """
     Raised by verifying methods of :class:`XEP_0373` on semantical verification errors.
@@ -688,7 +741,9 @@
 
         sign = signing_keys is not None
 
-        with gpg.Context(home_dir=self.__home_dir, signers=signers) as c:
+        kwargs = {"home_dir": self.__home_dir, "signers": signers}
+
+        with gpg.Context(**kwargs) as c:
             try:
                 ciphertext, __, __ = c.encrypt(
                     plaintext,
@@ -997,7 +1052,7 @@
 """
 
 
-def get_gpg_provider(sat: LiberviaBackend, client: SatXMPPClient) -> GPGProvider:
+def get_gpg_provider(sat: LiberviaBackend, client: SatXMPPEntity) -> GPGProvider:
     """Get the GPG provider for a client.
 
     @param sat: The SAT instance.