Coverage for tropicsquare / ports / cpython.py: 100%

24 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-03-27 21:24 +0000

1 

2from .. import TropicSquare 

3 

4from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat, PrivateFormat, NoEncryption 

5from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey 

6 

7from cryptography.hazmat.primitives.ciphers.aead import AESGCM 

8 

9from cryptography.hazmat.primitives.kdf.hkdf import HKDF 

10from cryptography.hazmat.primitives.hashes import SHA256 

11 

12 

13class TropicSquareCPython(TropicSquare): 

14 def __init__(self, transport): 

15 """Initialize TropicSquare for CPython. 

16 

17 :param transport: L1 transport instance 

18 """ 

19 

20 super().__init__(transport) 

21 

22 def _get_ephemeral_keypair(self): 

23 ehpriv = X25519PrivateKey.generate() 

24 ehpubraw = ehpriv.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) 

25 ehprivraw = ehpriv.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption()) 

26 

27 return (ehprivraw, ehpubraw) 

28 

29 

30 def _hkdf(self, salt, shared_secret, length = 1): 

31 result = HKDF(algorithm=SHA256(), 

32 length=length * 32, 

33 salt=salt, 

34 info=None).derive(shared_secret) 

35 

36 if length > 1: 

37 return [result[i*32:(i+1)*32] for i in range(length)] 

38 else: 

39 return result 

40 

41 

42 def _x25519_exchange(self, private_bytes, public_bytes): 

43 priv = X25519PrivateKey.from_private_bytes(private_bytes) 

44 return priv.exchange(X25519PublicKey.from_public_bytes(bytes(public_bytes))) 

45 

46 

47 def _aesgcm(self, key): 

48 return AESGCM(key)