Source code for fleetmesh_core.identity.didcomm

"""DIDComm v2 encrypted envelopes: ECDH-1PU authcrypt and ECDH-ES anoncrypt.

Everything two nodes say privately is DIDComm v2. constants.json names the
agreement as "ECDH-ES and ECDH-1PU as DIDComm v2 defines them" over X25519,
so this module is those two constructions and nothing else:

  authcrypt   alg ECDH-1PU+A256KW, enc A256CBC-HS512. The sender's static key
              is in the agreement, so the recipient knows who wrote it. Every
              message after first contact.
  anoncrypt   alg ECDH-ES+A256KW, enc A256CBC-HS512. First contact only,
              before the peer has any reason to reveal itself.

JWE JSON serialisation, general form, one or more recipients. The Concat KDF
is NIST SP 800-56A one-step with SHA-256 as RFC 7518 uses it; ECDH-1PU adds
the sender's static agreement to Z and, in key-wrapping mode, the content tag
to the KDF input so a recipient cannot re-target the message. Pinned in
node/tests/test_crypto.py to draft-madden-jose-ecdh-1pu-04 Appendix B, RFC 7518
Appendix C and RFC 3394.
"""
from __future__ import annotations

import base64
import hashlib
import hmac
import json
import os
import struct
from typing import Any, Callable, Mapping, Optional, Sequence, TypedDict

from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.asymmetric import x25519
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.keywrap import aes_key_wrap, aes_key_unwrap, InvalidUnwrap

from ..crypto import keys
from ..conformance.errors import FleetmeshError
from ..wire.interfaces import DIDCommMessage

TYP: str = 'application/didcomm-encrypted+json'
ENC: str = 'A256CBC-HS512'
AUTHCRYPT: str = 'ECDH-1PU+A256KW'
ANONCRYPT: str = 'ECDH-ES+A256KW'
KEK_BITS: dict[str, int] = {'A128KW': 128, 'A192KW': 192, 'A256KW': 256}


[docs]class JWERecipientHeader(TypedDict): kid: str
[docs]class JWERecipient(TypedDict): header: JWERecipientHeader encrypted_key: str
[docs]class JWE(TypedDict): protected: str recipients: list[JWERecipient] iv: str ciphertext: str tag: str
[docs]class JWEProtectedHeader(TypedDict, total=False): alg: str enc: str typ: str apv: str epk: Mapping[str, Any] skid: str apu: str
[docs]class EnvelopeError(FleetmeshError, ValueError): pass
[docs]def b64u(b: bytes) -> str: return base64.urlsafe_b64encode(b).rstrip(b'=').decode('ascii')
[docs]def b64u_dec(s: str) -> bytes: return base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))
def _len32(b: bytes) -> bytes: return struct.pack('>I', len(b)) + b # ------------------------------------------------------------ Concat KDF ----
[docs]def concat_kdf( z: bytes, alg: str, apu: bytes, apv: bytes, keydatalen_bits: int, cctag: Optional[bytes] = None, ) -> bytes: """NIST SP 800-56A one-step KDF, SHA-256, one round (every key here is <= 256 bits). FixedInfo = AlgorithmID || PartyUInfo || PartyVInfo || SuppPubInfo, each length-prefixed; SuppPubInfo is keydatalen and, for ECDH-1PU key wrap, the length-prefixed content tag. """ supp_pub = struct.pack('>I', keydatalen_bits) + (_len32(cctag) if cctag is not None else b'') fixed = _len32(alg.encode()) + _len32(apu) + _len32(apv) + supp_pub out = hashlib.sha256(struct.pack('>I', 1) + z + fixed).digest() return out[:keydatalen_bits // 8]
# --------------------------------------------------------- A256CBC-HS512 ----
[docs]def cbc_hs512_encrypt(cek: bytes, iv: bytes, plaintext: bytes, aad: bytes) -> tuple[bytes, bytes]: """RFC 7518 5.2.5. cek is 64 bytes: MAC key first, then the AES key.""" if len(cek) != 64 or len(iv) != 16: raise EnvelopeError('A256CBC-HS512 needs a 64-byte CEK and a 16-byte IV') mac_key, enc_key = cek[:32], cek[32:] padder = padding.PKCS7(128).padder() data = padder.update(plaintext) + padder.finalize() enc = Cipher(algorithms.AES(enc_key), modes.CBC(iv)).encryptor() ct = enc.update(data) + enc.finalize() al = struct.pack('>Q', len(aad) * 8) tag = hmac.new(mac_key, aad + iv + ct + al, hashlib.sha512).digest()[:32] return ct, tag
[docs]def cbc_hs512_decrypt(cek: bytes, iv: bytes, ct: bytes, tag: bytes, aad: bytes) -> bytes: # The same sizes the encrypt side insists on. A CEK of another length # comes only from an envelope whose key-wrap the sender controlled, and a # 15-byte IV would surface as a cryptography ValueError from inside the # cipher rather than the EnvelopeError every caller catches. if len(cek) != 64 or len(iv) != 16: raise EnvelopeError('A256CBC-HS512 needs a 64-byte CEK and a 16-byte IV') mac_key, enc_key = cek[:32], cek[32:] al = struct.pack('>Q', len(aad) * 8) expect = hmac.new(mac_key, aad + iv + ct + al, hashlib.sha512).digest()[:32] if not hmac.compare_digest(tag, expect): raise EnvelopeError('authentication tag does not verify') dec = Cipher(algorithms.AES(enc_key), modes.CBC(iv)).decryptor() data = dec.update(ct) + dec.finalize() unpadder = padding.PKCS7(128).unpadder() try: return unpadder.update(data) + unpadder.finalize() except ValueError as e: raise EnvelopeError('bad padding') from e
# ------------------------------------------------------------ agreements ----
[docs]def kek_1pu(alg: str, ze: bytes, zs: bytes, apu: bytes, apv: bytes, tag: bytes) -> bytes: """ECDH-1PU key-wrapping KEK: Z = Ze || Zs, tag in the KDF.""" return concat_kdf(ze + zs, alg, apu, apv, KEK_BITS[alg.split('+')[1]], cctag=tag)
[docs]def kek_es(alg: str, ze: bytes, apu: bytes, apv: bytes) -> bytes: return concat_kdf(ze, alg, apu, apv, KEK_BITS[alg.split('+')[1]])
[docs]def apv_for(recipient_kids: Sequence[str]) -> bytes: """DIDComm v2: base64url(SHA-256 of the sorted recipient kids joined by '.').""" return hashlib.sha256('.'.join(sorted(recipient_kids)).encode()).digest()
# -------------------------------------------------------------- envelopes ---- def _epk_header(eph_pub: x25519.X25519PublicKey) -> dict[str, str]: return {'kty': 'OKP', 'crv': 'X25519', 'x': b64u(keys.raw_public(eph_pub))}
[docs]def encrypt( plaintext_message: Any, recipients: Sequence[tuple[str, x25519.X25519PublicKey]], sender: Optional[tuple[str, x25519.X25519PrivateKey]] = None, eph_seed: Optional[bytes] = None, cek: Optional[bytes] = None, iv: Optional[bytes] = None, ) -> JWE: """A JWE for one plaintext message. recipients: [(kid, X25519PublicKey)]. sender: (skid, X25519PrivateKey) for authcrypt, None for anoncrypt. The seed, CEK and IV parameters exist for the vectors; a node never passes them. """ if not recipients: raise EnvelopeError('a message needs a recipient') body = json.dumps(plaintext_message, separators=(',', ':'), sort_keys=True, ensure_ascii=False).encode() eph_priv, eph_pub = keys.agreement_keypair(eph_seed) kids = [k for k, _ in recipients] apv = apv_for(kids) alg = AUTHCRYPT if sender else ANONCRYPT protected: JWEProtectedHeader = {'alg': alg, 'enc': ENC, 'typ': TYP, 'apv': b64u(apv), 'epk': _epk_header(eph_pub)} if sender: protected['skid'] = sender[0] protected['apu'] = b64u(sender[0].encode()) apu = sender[0].encode() else: apu = b'' protected_b64 = b64u(json.dumps(protected, separators=(',', ':'), sort_keys=True, ensure_ascii=False).encode()) aad = protected_b64.encode('ascii') cek = cek or os.urandom(64) iv = iv or os.urandom(16) ct, tag = cbc_hs512_encrypt(cek, iv, body, aad) recs: list[JWERecipient] = [] for kid, pub in recipients: ze = keys.x25519_shared(eph_priv, pub) if sender: kek = kek_1pu(alg, ze, keys.x25519_shared(sender[1], pub), apu, apv, tag) else: kek = kek_es(alg, ze, apu, apv) recs.append({'header': {'kid': kid}, 'encrypted_key': b64u(aes_key_wrap(kek, cek))}) return {'protected': protected_b64, 'recipients': recs, 'iv': b64u(iv), 'ciphertext': b64u(ct), 'tag': b64u(tag)}
[docs]def decrypt( jwe: Mapping[str, Any], my_kid: str, my_priv: x25519.X25519PrivateKey, resolve_sender: Optional[Callable[[str], Optional[x25519.X25519PublicKey]]] = None, ) -> tuple[DIDCommMessage, Optional[str]]: """Open a JWE addressed to my_kid. For authcrypt, resolve_sender(skid) must return the sender's static X25519 public key; the sender is then authenticated by the agreement itself. Returns (message, skid or None).""" try: protected = json.loads(b64u_dec(jwe['protected'])) except Exception as e: raise EnvelopeError('protected header is not JSON') from e if not isinstance(protected, Mapping): raise EnvelopeError('protected header is not a JSON object') alg, enc = protected.get('alg'), protected.get('enc') if enc != ENC or alg not in (AUTHCRYPT, ANONCRYPT): raise EnvelopeError('unsupported alg/enc %s/%s' % (alg, enc)) recipients = jwe.get('recipients', []) if not isinstance(recipients, list): raise EnvelopeError('recipients must be a list') rec = next((r for r in recipients if isinstance(r, Mapping) and isinstance(r.get('header'), Mapping) and r['header'].get('kid') == my_kid), None) if rec is None: raise EnvelopeError('not addressed to %s' % my_kid) epk = protected.get('epk', {}) if not isinstance(epk, Mapping) or epk.get('kty') != 'OKP' or epk.get('crv') != 'X25519': raise EnvelopeError('epk must be an X25519 OKP key') try: eph_pub = keys.agreement_public(b64u_dec(epk.get('x') or '')) except (ValueError, TypeError) as e: raise EnvelopeError('epk is not an X25519 key: %s' % e) try: apv = b64u_dec(protected.get('apv', '')) apu = b64u_dec(protected.get('apu', '')) except (ValueError, TypeError) as e: raise EnvelopeError('invalid apu/apv encoding: %s' % e) if 'apv' in protected and apv != apv_for([ r['header']['kid'] for r in recipients if isinstance(r, Mapping) and isinstance(r.get('header'), Mapping) and isinstance(r['header'].get('kid'), str) ]): raise EnvelopeError('apv does not match recipients') try: tag = b64u_dec(jwe['tag']) iv_bytes = b64u_dec(jwe['iv']) ct_bytes = b64u_dec(jwe['ciphertext']) enc_key_bytes = b64u_dec(rec['encrypted_key']) except (KeyError, TypeError, ValueError): raise EnvelopeError('a JWE has protected, recipients with encrypted_key, iv, ciphertext and tag') ze = keys.x25519_shared(my_priv, eph_pub) skid = None if alg == AUTHCRYPT: skid = protected.get('skid') if not skid or resolve_sender is None: raise EnvelopeError('authcrypt needs a skid and a way to resolve it') if apu != skid.encode(): raise EnvelopeError('apu does not name the skid') sender_pub = resolve_sender(skid) if sender_pub is None: raise EnvelopeError('unknown sender %s' % skid) kek = kek_1pu(alg, ze, keys.x25519_shared(my_priv, sender_pub), apu, apv, tag) else: kek = kek_es(alg, ze, apu, apv) try: cek = aes_key_unwrap(kek, enc_key_bytes) except InvalidUnwrap: raise EnvelopeError('key unwrap failed: wrong recipient key or tampered envelope') aad = jwe['protected'].encode('ascii') body = cbc_hs512_decrypt(cek, iv_bytes, ct_bytes, tag, aad) try: return json.loads(body), skid except ValueError: raise EnvelopeError('plaintext is not a JSON message')