Coverage for oarepo_c4gh/key/writer.py: 100%

13 statements  

« prev     ^ index     » next       coverage.py v7.10.2, created at 2025-08-07 12:05 +0000

1"""This module provides (very simple) means of serializing any 

2c4gh-compatible key into c4gh textual representation. For example a 

3HSM-backed key can be exported as c4gh public key which can be in turn 

4loaded into client software that will use it to encrypt the data for 

5this key. 

6 

7""" 

8 

9from .key import Key 

10import io 

11from base64 import b64encode 

12 

13 

14class C4GHPublicKeyWriter: 

15 """Very simple writer class that can be extended in the future. At 

16 the moment it serves as a thin layer between any Key 

17 implementation and textual serialization functions. 

18 

19 """ 

20 

21 def __init__(self, key: Key) -> None: 

22 """Initializes the writer with given Key instance. 

23 

24 Parameters: 

25 key: the key to be serialized 

26 """ 

27 self._key = key 

28 

29 def __str__(self) -> str: 

30 """Returns the string version of serialized public key in 

31 Crypt4GH native format. 

32 

33 """ 

34 b64key = b64encode(self._key.public_key).decode("ascii") 

35 return ( 

36 f"-----BEGIN CRYPT4GH PUBLIC KEY-----\n" 

37 f"{b64key}\n" 

38 f"-----END CRYPT4GH PUBLIC KEY-----\n" 

39 ) 

40 

41 def __bytes__(self) -> bytes: 

42 """The same as the string conversion - this time as bytes (the 

43 underlying encoding is 7-bit ASCII anyway). 

44 

45 """ 

46 return str(self).encode("ascii") 

47 

48 def write(self, ostream: io.RawIOBase) -> None: 

49 """Writes the serialized key into given IO stream. 

50 

51 Parameters: 

52 ostream: where to write the key to 

53 """ 

54 ostream.write(bytes(self))