Source code for fleetmesh_core.crypto.ssb

"""Secure Scuttlebutt (SSB) Cryptography: Secret Handshake (SSB-SHS) & Box Stream (SSB-BoxStream).

Standard library and cryptography (Poly1305, Ed25519, X25519) only.
Supports:
- Dominic Tarr's 4-phase Secret Handshake (SSB-SHS) authenticated key exchange.
- Birational Ed25519 <-> Curve25519 (X25519) point and scalar translation.
- Verified XSalsa20-Poly1305 symmetric authenticated encryption (crypto_secretbox).
- Box Stream (SSB-BoxStream) 34-byte packet framing with Poly1305 MAC tag and goodbye termination.
- SSB feed identity format (@<base64>.ed25519).
"""
from __future__ import annotations

import base64
import hashlib
import hmac
import struct
from typing import Optional, Sequence, Tuple

from cryptography.hazmat.primitives.asymmetric import ed25519, x25519
from cryptography.hazmat.primitives.poly1305 import Poly1305

from ..conformance.errors import FleetmeshError

__all__ = [
    'SSBCryptoError',
    'SSB_MAINNET_NETWORK_KEY',
    'BOX_STREAM_HEADER_LENGTH',
    'BOX_STREAM_MAX_PAYLOAD',
    'BOX_STREAM_TERMINATION',
    'format_ssb_feed_id',
    'parse_ssb_feed_id',
    'ed25519_pk_to_curve25519',
    'ed25519_sk_to_curve25519',
    'crypto_auth',
    'crypto_auth_verify',
    'crypto_secretbox_easy',
    'crypto_secretbox_open_easy',
    'inc_nonce',
    'SHSClient',
    'SHSServer',
    'BoxStreamEncryptor',
    'BoxStreamDecryptor',
]

# Standard SSB mainnet capability / network key
SSB_MAINNET_NETWORK_KEY = bytes.fromhex('d4a1cb88a66f02f8db635ce26441cc5dac1b08420ceaac230839b755845a9ffb')

BOX_STREAM_HEADER_LENGTH = 34
BOX_STREAM_MAX_PAYLOAD = 4096
BOX_STREAM_TERMINATION = b'\x00' * 18

_P25519 = 2**255 - 19
_SIGMA = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574]


[docs]class SSBCryptoError(FleetmeshError): """Base error for Secure Scuttlebutt cryptographic operations."""
# ----------------------------------------------------------------------------- # Identity Key Formats # -----------------------------------------------------------------------------
[docs]def format_ssb_feed_id(ed25519_pk: bytes) -> str: """Format 32-byte Ed25519 public key as SSB feed ID (@<base64>.ed25519).""" if len(ed25519_pk) != 32: raise SSBCryptoError(f"invalid Ed25519 public key length: {len(ed25519_pk)}") b64 = base64.b64encode(ed25519_pk).decode('ascii') return f"@{b64}.ed25519"
[docs]def parse_ssb_feed_id(feed_id: str) -> bytes: """Parse SSB feed ID string into 32-byte Ed25519 public key.""" s = feed_id.strip() if not (s.startswith('@') and s.endswith('.ed25519')): raise SSBCryptoError(f"invalid SSB feed ID format: {feed_id}") b64 = s[1:-8] try: raw = base64.b64decode(b64) if len(raw) != 32: raise SSBCryptoError(f"decoded key is not 32 bytes: {len(raw)}") return raw except Exception as e: raise SSBCryptoError(f"failed to decode base64 in feed ID: {e}") from e
# ----------------------------------------------------------------------------- # Birational Ed25519 <-> Curve25519 (X25519) Mapping # -----------------------------------------------------------------------------
[docs]def ed25519_pk_to_curve25519(ed_pk: bytes) -> bytes: """Map Ed25519 public key to Curve25519 (X25519) u-coordinate: u = (1 + y) / (1 - y) mod p.""" if len(ed_pk) != 32: raise SSBCryptoError(f"invalid Ed25519 pubkey length: {len(ed_pk)}") y = int.from_bytes(ed_pk, 'little') & ((1 << 255) - 1) u = ((1 + y) * pow(1 - y, _P25519 - 2, _P25519)) % _P25519 return u.to_bytes(32, 'little')
[docs]def ed25519_sk_to_curve25519(ed_sk: bytes) -> bytes: """Derive Curve25519 private scalar from Ed25519 private seed.""" if len(ed_sk) != 32: raise SSBCryptoError(f"invalid Ed25519 private seed length: {len(ed_sk)}") h = bytearray(hashlib.sha512(ed_sk).digest()[:32]) h[0] &= 248 h[31] &= 127 h[31] |= 64 return bytes(h)
# ----------------------------------------------------------------------------- # NaCl crypto_auth (HMAC-SHA-512-256) # -----------------------------------------------------------------------------
[docs]def crypto_auth(msg: bytes, key: bytes) -> bytes: """NaCl crypto_auth: first 32 bytes of HMAC-SHA-512.""" return hmac.new(key, msg, hashlib.sha512).digest()[:32]
[docs]def crypto_auth_verify(tag: bytes, msg: bytes, key: bytes) -> bool: """Verify NaCl crypto_auth tag in constant time.""" expected = crypto_auth(msg, key) return hmac.compare_digest(tag, expected)
# ----------------------------------------------------------------------------- # NaCl crypto_secretbox (XSalsa20-Poly1305) # ----------------------------------------------------------------------------- def _rotl(a: int, b: int) -> int: return ((a << b) & 0xffffffff) | (a >> (32 - b)) def _salsa_core(x: Sequence[int]) -> list[int]: y = list(x) for _ in range(10): # Column round y[4] ^= _rotl((y[0] + y[12]) & 0xffffffff, 7) y[8] ^= _rotl((y[4] + y[0]) & 0xffffffff, 9) y[12] ^= _rotl((y[8] + y[4]) & 0xffffffff, 13) y[0] ^= _rotl((y[12] + y[8]) & 0xffffffff, 18) y[9] ^= _rotl((y[5] + y[1]) & 0xffffffff, 7) y[13] ^= _rotl((y[9] + y[5]) & 0xffffffff, 9) y[1] ^= _rotl((y[13] + y[9]) & 0xffffffff, 13) y[5] ^= _rotl((y[1] + y[13]) & 0xffffffff, 18) y[14] ^= _rotl((y[10] + y[6]) & 0xffffffff, 7) y[2] ^= _rotl((y[14] + y[10]) & 0xffffffff, 9) y[6] ^= _rotl((y[2] + y[14]) & 0xffffffff, 13) y[10] ^= _rotl((y[6] + y[2]) & 0xffffffff, 18) y[3] ^= _rotl((y[15] + y[11]) & 0xffffffff, 7) y[7] ^= _rotl((y[3] + y[15]) & 0xffffffff, 9) y[11] ^= _rotl((y[7] + y[3]) & 0xffffffff, 13) y[15] ^= _rotl((y[11] + y[7]) & 0xffffffff, 18) # Row round y[1] ^= _rotl((y[0] + y[3]) & 0xffffffff, 7) y[2] ^= _rotl((y[1] + y[0]) & 0xffffffff, 9) y[3] ^= _rotl((y[2] + y[1]) & 0xffffffff, 13) y[0] ^= _rotl((y[3] + y[2]) & 0xffffffff, 18) y[6] ^= _rotl((y[5] + y[4]) & 0xffffffff, 7) y[7] ^= _rotl((y[6] + y[5]) & 0xffffffff, 9) y[4] ^= _rotl((y[7] + y[6]) & 0xffffffff, 13) y[5] ^= _rotl((y[4] + y[7]) & 0xffffffff, 18) y[11] ^= _rotl((y[10] + y[9]) & 0xffffffff, 7) y[8] ^= _rotl((y[11] + y[10]) & 0xffffffff, 9) y[9] ^= _rotl((y[8] + y[11]) & 0xffffffff, 13) y[10] ^= _rotl((y[9] + y[8]) & 0xffffffff, 18) y[12] ^= _rotl((y[15] + y[14]) & 0xffffffff, 7) y[13] ^= _rotl((y[12] + y[15]) & 0xffffffff, 9) y[14] ^= _rotl((y[13] + y[12]) & 0xffffffff, 13) y[15] ^= _rotl((y[14] + y[13]) & 0xffffffff, 18) return y def hsalsa20(input_16: bytes, key_32: bytes) -> bytes: """HSalsa20 core key derivation function for XSalsa20.""" k = struct.unpack('<8I', key_32) in_u = struct.unpack('<4I', input_16) x = [ _SIGMA[0], k[0], k[1], k[2], k[3], _SIGMA[1], in_u[0], in_u[1], in_u[2], in_u[3], _SIGMA[2], k[4], k[5], k[6], k[7], _SIGMA[3] ] y = _salsa_core(x) return struct.pack('<8I', y[0], y[5], y[10], y[15], y[6], y[7], y[8], y[9]) def salsa20_keystream(key_32: bytes, nonce_8: bytes, counter_8: int, num_bytes: int) -> bytes: """Generate Salsa20 keystream blocks.""" k = struct.unpack('<8I', key_32) n = struct.unpack('<2I', nonce_8) blocks = [] ctr = counter_8 bytes_generated = 0 while bytes_generated < num_bytes: c0 = ctr & 0xffffffff c1 = (ctr >> 32) & 0xffffffff x = [ _SIGMA[0], k[0], k[1], k[2], k[3], _SIGMA[1], n[0], n[1], c0, c1, _SIGMA[2], k[4], k[5], k[6], k[7], _SIGMA[3] ] y = _salsa_core(x) out = [(x[i] + y[i]) & 0xffffffff for i in range(16)] block = struct.pack('<16I', *out) blocks.append(block) bytes_generated += 64 ctr += 1 return b''.join(blocks)[:num_bytes]
[docs]def crypto_secretbox_easy(m: bytes, nonce: bytes, key: bytes) -> bytes: """NaCl crypto_secretbox_easy: XSalsa20-Poly1305 authenticated encryption.""" if len(key) != 32: raise SSBCryptoError(f"key must be 32 bytes, got {len(key)}") if len(nonce) != 24: raise SSBCryptoError(f"nonce must be 24 bytes, got {len(nonce)}") subkey = hsalsa20(nonce[:16], key) salsa_nonce = nonce[16:24] ks = salsa20_keystream(subkey, salsa_nonce, 0, len(m) + 32) poly_key = ks[:32] ciphertext = bytes(p ^ k for p, k in zip(m, ks[32:])) tag = Poly1305.generate_tag(poly_key, ciphertext) return tag + ciphertext
[docs]def crypto_secretbox_open_easy(c: bytes, nonce: bytes, key: bytes) -> bytes: """NaCl crypto_secretbox_open_easy: verify and decrypt.""" if len(c) < 16: raise SSBCryptoError("ciphertext must be at least 16 bytes (MAC tag)") if len(key) != 32: raise SSBCryptoError(f"key must be 32 bytes, got {len(key)}") if len(nonce) != 24: raise SSBCryptoError(f"nonce must be 24 bytes, got {len(nonce)}") tag = c[:16] ciphertext = c[16:] subkey = hsalsa20(nonce[:16], key) salsa_nonce = nonce[16:24] ks = salsa20_keystream(subkey, salsa_nonce, 0, len(ciphertext) + 32) poly_key = ks[:32] try: Poly1305.verify_tag(poly_key, ciphertext, tag) except Exception as e: raise SSBCryptoError("ciphertext tag verification failed (tampered or wrong key)") from e return bytes(p ^ k for p, k in zip(ciphertext, ks[32:]))
[docs]def inc_nonce(nonce: bytes) -> bytes: """Increment big-endian 24-byte nonce mod 2^192.""" if len(nonce) != 24: raise SSBCryptoError(f"nonce must be 24 bytes, got {len(nonce)}") num = (int.from_bytes(nonce, 'big') + 1) % (1 << 192) return num.to_bytes(24, 'big')
# ----------------------------------------------------------------------------- # Secret Handshake (SHS) Engine # -----------------------------------------------------------------------------
[docs]class SHSClient: """Client-side state machine for 4-phase Secret Handshake."""
[docs] def __init__( self, local_ed25519_sk: bytes, server_ed25519_pk: bytes, network_key: bytes = SSB_MAINNET_NETWORK_KEY, ephemeral_sk: Optional[bytes] = None, ): self.local_ed_sk = local_ed25519_sk self.local_ed_priv = ed25519.Ed25519PrivateKey.from_private_bytes(local_ed25519_sk) self.local_ed_pk = self.local_ed_priv.public_key().public_bytes_raw() self.server_ed_pk = server_ed25519_pk self.network_key = network_key if ephemeral_sk: self.ephem_priv = x25519.X25519PrivateKey.from_private_bytes(ephemeral_sk) else: self.ephem_priv = x25519.X25519PrivateKey.generate() self.ephem_pk = self.ephem_priv.public_key().public_bytes_raw() self.client_hmac = crypto_auth(self.ephem_pk, self.network_key) self.server_ephem_pk: Optional[bytes] = None self.server_hmac: Optional[bytes] = None self.shared_ab: Optional[bytes] = None self.shared_hash: Optional[bytes] = None self.shared_aB: Optional[bytes] = None self.shared_Ab: Optional[bytes] = None self.client_sig: Optional[bytes] = None self.box4_key: Optional[bytes] = None
[docs] def create_client_hello(self) -> bytes: """Phase 1: Produce Client Hello (64 bytes).""" return self.client_hmac + self.ephem_pk
[docs] def verify_server_hello(self, msg2: bytes) -> None: """Phase 2: Verify Server Hello (64 bytes) and derive initial shared secrets.""" if len(msg2) != 64: raise SSBCryptoError(f"server hello must be 64 bytes, got {len(msg2)}") sent_hmac = msg2[:32] server_ephem_pk = msg2[32:] if not crypto_auth_verify(sent_hmac, server_ephem_pk, self.network_key): raise SSBCryptoError("server hello HMAC verification failed (network key mismatch)") self.server_hmac = sent_hmac self.server_ephem_pk = server_ephem_pk # Scalar multiplication: a * b remote_ephem_pub = x25519.X25519PublicKey.from_public_bytes(server_ephem_pk) self.shared_ab = self.ephem_priv.exchange(remote_ephem_pub) self.shared_hash = hashlib.sha256(self.shared_ab).digest() # Scalar multiplication: a * B server_curve_pk = ed25519_pk_to_curve25519(self.server_ed_pk) server_curve_pub = x25519.X25519PublicKey.from_public_bytes(server_curve_pk) self.shared_aB = self.ephem_priv.exchange(server_curve_pub)
[docs] def create_client_authenticate(self) -> bytes: """Phase 3: Produce Client Authenticate message (112 bytes).""" if self.shared_ab is None or self.shared_aB is None or self.shared_hash is None: raise SSBCryptoError("must call verify_server_hello before creating client authenticate") sig_data = self.network_key + self.server_ed_pk + self.shared_hash self.client_sig = self.local_ed_priv.sign(sig_data) msg3_plain = self.client_sig + self.local_ed_pk box3_key = hashlib.sha256(self.network_key + self.shared_ab + self.shared_aB).digest() return crypto_secretbox_easy(msg3_plain, b'\x00' * 24, box3_key)
[docs] def verify_server_accept(self, msg4: bytes) -> None: """Phase 4: Verify Server Accept message (80 bytes).""" if len(msg4) != 80: raise SSBCryptoError(f"server accept must be 80 bytes, got {len(msg4)}") if (self.server_ephem_pk is None or self.client_sig is None or self.shared_ab is None or self.shared_aB is None or self.shared_hash is None): raise SSBCryptoError("invalid handshake state for phase 4") # Scalar multiplication: A * b local_curve_sk = ed25519_sk_to_curve25519(self.local_ed_sk) local_curve_priv = x25519.X25519PrivateKey.from_private_bytes(local_curve_sk) remote_ephem_pub = x25519.X25519PublicKey.from_public_bytes(self.server_ephem_pk) self.shared_Ab = local_curve_priv.exchange(remote_ephem_pub) self.box4_key = hashlib.sha256(self.network_key + self.shared_ab + self.shared_aB + self.shared_Ab).digest() server_sig = crypto_secretbox_open_easy(msg4, b'\x00' * 24, self.box4_key) expected_sig_data = self.network_key + self.client_sig + self.local_ed_pk + self.shared_hash server_pub = ed25519.Ed25519PublicKey.from_public_bytes(self.server_ed_pk) try: server_pub.verify(server_sig, expected_sig_data) except Exception as e: raise SSBCryptoError("server acceptance signature verification failed") from e
[docs] def get_box_stream_keys(self) -> Tuple[bytes, bytes, bytes, bytes]: """Derive (encrypt_key, encrypt_nonce, decrypt_key, decrypt_nonce) for Box Stream.""" if self.box4_key is None or self.server_hmac is None: raise SSBCryptoError("handshake not completed") shared_secret = hashlib.sha256(self.box4_key).digest() encrypt_key = hashlib.sha256(shared_secret + self.server_ed_pk).digest() decrypt_key = hashlib.sha256(shared_secret + self.local_ed_pk).digest() encrypt_nonce = self.server_hmac[:24] decrypt_nonce = self.client_hmac[:24] return encrypt_key, encrypt_nonce, decrypt_key, decrypt_nonce
[docs]class SHSServer: """Server-side state machine for 4-phase Secret Handshake."""
[docs] def __init__( self, local_ed25519_sk: bytes, network_key: bytes = SSB_MAINNET_NETWORK_KEY, ephemeral_sk: Optional[bytes] = None, ): self.local_ed_sk = local_ed25519_sk self.local_ed_priv = ed25519.Ed25519PrivateKey.from_private_bytes(local_ed25519_sk) self.local_ed_pk = self.local_ed_priv.public_key().public_bytes_raw() self.network_key = network_key if ephemeral_sk: self.ephem_priv = x25519.X25519PrivateKey.from_private_bytes(ephemeral_sk) else: self.ephem_priv = x25519.X25519PrivateKey.generate() self.ephem_pk = self.ephem_priv.public_key().public_bytes_raw() self.server_hmac = crypto_auth(self.ephem_pk, self.network_key) self.client_ephem_pk: Optional[bytes] = None self.client_hmac: Optional[bytes] = None self.shared_ab: Optional[bytes] = None self.shared_hash: Optional[bytes] = None self.shared_aB: Optional[bytes] = None self.shared_Ab: Optional[bytes] = None self.client_ed_pk: Optional[bytes] = None self.client_sig: Optional[bytes] = None self.box4_key: Optional[bytes] = None
[docs] def verify_client_hello(self, msg1: bytes) -> None: """Phase 1: Verify Client Hello (64 bytes).""" if len(msg1) != 64: raise SSBCryptoError(f"client hello must be 64 bytes, got {len(msg1)}") sent_hmac = msg1[:32] client_ephem_pk = msg1[32:] if not crypto_auth_verify(sent_hmac, client_ephem_pk, self.network_key): raise SSBCryptoError("client hello HMAC verification failed (network key mismatch)") self.client_hmac = sent_hmac self.client_ephem_pk = client_ephem_pk # Scalar multiplication: a * b remote_ephem_pub = x25519.X25519PublicKey.from_public_bytes(client_ephem_pk) self.shared_ab = self.ephem_priv.exchange(remote_ephem_pub) self.shared_hash = hashlib.sha256(self.shared_ab).digest() # Scalar multiplication: a * B local_curve_sk = ed25519_sk_to_curve25519(self.local_ed_sk) local_curve_priv = x25519.X25519PrivateKey.from_private_bytes(local_curve_sk) self.shared_aB = local_curve_priv.exchange(remote_ephem_pub)
[docs] def create_server_hello(self) -> bytes: """Phase 2: Produce Server Hello (64 bytes).""" return self.server_hmac + self.ephem_pk
[docs] def verify_client_authenticate(self, msg3: bytes) -> bytes: """Phase 3: Verify Client Authenticate (112 bytes) and return client Ed25519 pubkey.""" if len(msg3) != 112: raise SSBCryptoError(f"client authenticate must be 112 bytes, got {len(msg3)}") if self.shared_ab is None or self.shared_aB is None or self.shared_hash is None: raise SSBCryptoError("invalid handshake state for phase 3") box3_key = hashlib.sha256(self.network_key + self.shared_ab + self.shared_aB).digest() msg3_plain = crypto_secretbox_open_easy(msg3, b'\x00' * 24, box3_key) client_sig = msg3_plain[:64] client_ed_pk = msg3_plain[64:] expected_sig_data = self.network_key + self.local_ed_pk + self.shared_hash client_pub = ed25519.Ed25519PublicKey.from_public_bytes(client_ed_pk) try: client_pub.verify(client_sig, expected_sig_data) except Exception as e: raise SSBCryptoError("client identity signature verification failed") from e self.client_sig = client_sig self.client_ed_pk = client_ed_pk return client_ed_pk
[docs] def create_server_accept(self) -> bytes: """Phase 4: Produce Server Accept message (80 bytes).""" if (self.client_ed_pk is None or self.client_sig is None or self.shared_ab is None or self.shared_aB is None or self.shared_hash is None): raise SSBCryptoError("must verify client authenticate before creating server accept") client_curve_pk = ed25519_pk_to_curve25519(self.client_ed_pk) client_curve_pub = x25519.X25519PublicKey.from_public_bytes(client_curve_pk) self.shared_Ab = self.ephem_priv.exchange(client_curve_pub) self.box4_key = hashlib.sha256(self.network_key + self.shared_ab + self.shared_aB + self.shared_Ab).digest() sig_data = self.network_key + self.client_sig + self.client_ed_pk + self.shared_hash server_sig = self.local_ed_priv.sign(sig_data) return crypto_secretbox_easy(server_sig, b'\x00' * 24, self.box4_key)
[docs] def get_box_stream_keys(self) -> Tuple[bytes, bytes, bytes, bytes]: """Derive (encrypt_key, encrypt_nonce, decrypt_key, decrypt_nonce) for Box Stream.""" if self.box4_key is None or self.client_ed_pk is None or self.client_hmac is None: raise SSBCryptoError("handshake not completed") shared_secret = hashlib.sha256(self.box4_key).digest() encrypt_key = hashlib.sha256(shared_secret + self.client_ed_pk).digest() decrypt_key = hashlib.sha256(shared_secret + self.local_ed_pk).digest() encrypt_nonce = self.client_hmac[:24] decrypt_nonce = self.server_hmac[:24] return encrypt_key, encrypt_nonce, decrypt_key, decrypt_nonce
# ----------------------------------------------------------------------------- # Box Stream Encryptor & Decryptor # -----------------------------------------------------------------------------
[docs]class BoxStreamEncryptor: """Frames and encrypts duplex stream packets."""
[docs] def __init__(self, key: bytes, starting_nonce: bytes): if len(key) != 32 or len(starting_nonce) != 24: raise SSBCryptoError("invalid key or nonce length for BoxStreamEncryptor") self.key = key self.nonce = starting_nonce
[docs] def encrypt_packet(self, data: bytes) -> bytes: """Encrypt data packet into 34-byte header followed by ciphertext body.""" if len(data) > BOX_STREAM_MAX_PAYLOAD: raise SSBCryptoError(f"packet payload exceeds {BOX_STREAM_MAX_PAYLOAD} bytes: {len(data)}") body_box = crypto_secretbox_easy(data, inc_nonce(self.nonce), self.key) tag = body_box[:16] ciphertext = body_box[16:] hdr_plain = struct.pack('>H', len(ciphertext)) + tag hdr_box = crypto_secretbox_easy(hdr_plain, self.nonce, self.key) self.nonce = inc_nonce(inc_nonce(self.nonce)) return hdr_box + ciphertext
[docs] def encrypt_goodbye(self) -> bytes: """Produce 34-byte authenticated termination header.""" hdr_box = crypto_secretbox_easy(BOX_STREAM_TERMINATION, self.nonce, self.key) self.nonce = inc_nonce(inc_nonce(self.nonce)) return hdr_box
[docs]class BoxStreamDecryptor: """Decrypts 34-byte headers and payload bodies from Box Stream."""
[docs] def __init__(self, key: bytes, starting_nonce: bytes): if len(key) != 32 or len(starting_nonce) != 24: raise SSBCryptoError("invalid key or nonce length for BoxStreamDecryptor") self.key = key self.nonce = starting_nonce
[docs] def decrypt_header(self, hdr_box_34: bytes) -> Tuple[Optional[int], Optional[bytes]]: """Decrypt 34-byte header. Returns (payload_length, body_tag_16). If stream has closed via goodbye, returns (None, None). """ if len(hdr_box_34) != BOX_STREAM_HEADER_LENGTH: raise SSBCryptoError(f"header must be {BOX_STREAM_HEADER_LENGTH} bytes, got {len(hdr_box_34)}") hdr_plain = crypto_secretbox_open_easy(hdr_box_34, self.nonce, self.key) if hdr_plain == BOX_STREAM_TERMINATION: self.nonce = inc_nonce(inc_nonce(self.nonce)) return None, None length = struct.unpack('>H', hdr_plain[:2])[0] tag = hdr_plain[2:18] return length, tag
[docs] def decrypt_body(self, tag_16: bytes, ciphertext: bytes) -> bytes: """Decrypt payload body using tag extracted from header.""" if len(tag_16) != 16: raise SSBCryptoError(f"tag must be 16 bytes, got {len(tag_16)}") body_box = tag_16 + ciphertext body = crypto_secretbox_open_easy(body_box, inc_nonce(self.nonce), self.key) self.nonce = inc_nonce(inc_nonce(self.nonce)) return body