Source code for fleetmesh_core.crypto.nip44

"""NIP-44 v2: the envelope scheme constants.json names as nip44/2.

ChaCha20 with HMAC-SHA256 in encrypt-then-MAC. The conversation key is
HKDF-extract over the secp256k1 ECDH x-coordinate under the salt "nip44-v2";
per message, HKDF-expand under the 32-byte nonce yields the cipher key, the
cipher nonce and the MAC key. Plaintext is length-prefixed and padded to a
power-of-two schedule so message sizes leak less.

Used by kind 30801 and 30811 content, the compute ask's enc field, and the
NIP-59 gift wraps this node uses as its transport. Pinned to the vectors
published with the NIP (meshnode: node/tests/testdata/nip44.vectors.json).

This module needs the `cryptography` package for ChaCha20, as didcomm.py does.
"""
from __future__ import annotations

import base64
import hmac
import hashlib
import math
import os
from typing import Optional

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms

from . import crypto

VERSION: int = 2
SALT: bytes = b'nip44-v2'
MIN_PLAINTEXT, MAX_PLAINTEXT = 1, 65535
MIN_PAYLOAD, MAX_PAYLOAD = 132, 87472


[docs]class Nip44Error(ValueError): pass
[docs]def conversation_key(sec_hex: str, pub_hex: str) -> bytes: """HKDF-extract(salt="nip44-v2", ikm=ECDH x-coordinate). Symmetric in the pair.""" try: crypto._scalar(sec_hex) except ValueError as e: raise Nip44Error(str(e)) try: shared_x = bytes.fromhex(crypto.ecdh_x(sec_hex, pub_hex)) except (ValueError, TypeError, ArithmeticError) as e: raise Nip44Error('public key is not a point on the curve: %s' % e) return hmac.new(SALT, shared_x, hashlib.sha256).digest()
def _hkdf_expand(prk: bytes, info: bytes, length: int) -> bytes: out, t, i = b'', b'', 1 while len(out) < length: t = hmac.new(prk, t + info + bytes([i]), hashlib.sha256).digest() out += t i += 1 return out[:length]
[docs]def message_keys(conv_key: bytes, nonce: bytes) -> tuple[bytes, bytes, bytes]: """(chacha_key, chacha_nonce, hmac_key) = HKDF-expand(conv_key, nonce, 76).""" if len(nonce) != 32: raise Nip44Error('nonce must be 32 bytes') k = _hkdf_expand(conv_key, nonce, 76) return k[:32], k[32:44], k[44:76]
[docs]def calc_padded_len(unpadded_len: int) -> int: """The schedule alone. pad() enforces the 1..65535 limit; the NIP's own vectors exercise this function past it.""" if unpadded_len < 1: raise Nip44Error('invalid plaintext length %d' % unpadded_len) if unpadded_len <= 32: return 32 next_power = 1 << (int(math.floor(math.log2(unpadded_len - 1))) + 1) chunk = 32 if next_power <= 256 else next_power // 8 return chunk * ((unpadded_len - 1) // chunk + 1)
[docs]def pad(plaintext: str | bytes) -> bytes: data = plaintext.encode('utf-8') if isinstance(plaintext, str) else plaintext n = len(data) if not (MIN_PLAINTEXT <= n <= MAX_PLAINTEXT): raise Nip44Error('invalid plaintext length %d' % n) return n.to_bytes(2, 'big') + data + b'\x00' * (calc_padded_len(n) - n)
[docs]def unpad(padded: bytes) -> bytes: if len(padded) < 2: raise Nip44Error('invalid padding') n = int.from_bytes(padded[:2], 'big') if n == 0 or n > MAX_PLAINTEXT or len(padded) != 2 + calc_padded_len(n): raise Nip44Error('invalid padding') return padded[2:2 + n]
def _chacha(key: bytes, nonce12: bytes, data: bytes) -> bytes: # cryptography takes a 16-byte nonce: 32-bit little-endian block counter, then the 96-bit nonce. cipher = Cipher(algorithms.ChaCha20(key, b'\x00' * 4 + nonce12), mode=None) enc = cipher.encryptor() return enc.update(data) + enc.finalize()
[docs]def encrypt(plaintext: str | bytes, conv_key: bytes, nonce: Optional[bytes] = None) -> str: nonce = nonce or os.urandom(32) chacha_key, chacha_nonce, hmac_key = message_keys(conv_key, nonce) ciphertext = _chacha(chacha_key, chacha_nonce, pad(plaintext)) mac = hmac.new(hmac_key, nonce + ciphertext, hashlib.sha256).digest() return base64.b64encode(bytes([VERSION]) + nonce + ciphertext + mac).decode('ascii')
[docs]def decode_payload(payload: str) -> tuple[bytes, bytes, bytes]: """(nonce, ciphertext, mac). Every length check the NIP lists, before any crypto.""" if not payload: raise Nip44Error('empty payload') if payload[0] == '#': raise Nip44Error('unknown version') if not (MIN_PAYLOAD <= len(payload) <= MAX_PAYLOAD): raise Nip44Error('invalid payload length %d' % len(payload)) try: data = base64.b64decode(payload, validate=True) except Exception: raise Nip44Error('payload is not base64') if not (99 <= len(data) <= 65603): raise Nip44Error('invalid data length %d' % len(data)) if data[0] != VERSION: raise Nip44Error('unknown version %d' % data[0]) return data[1:33], data[33:-32], data[-32:]
[docs]def decrypt_bytes(payload: str, conv_key: bytes) -> bytes: nonce, ciphertext, mac = decode_payload(payload) chacha_key, chacha_nonce, hmac_key = message_keys(conv_key, nonce) expected = hmac.new(hmac_key, nonce + ciphertext, hashlib.sha256).digest() if not hmac.compare_digest(mac, expected): raise Nip44Error('invalid MAC') return unpad(_chacha(chacha_key, chacha_nonce, ciphertext))
[docs]def decrypt(payload: str, conv_key: bytes) -> str: return decrypt_bytes(payload, conv_key).decode('utf-8')