44from Crypto .PublicKey import RSA
55
66
7- class Encoder :
8- def __init__ (self , private_key : str = None , public_key : str = None ):
9- assert private_key or public_key , "private_key or/and public_key need to be given"
10- if private_key :
11- self ._private_key = self .load_key (key = private_key .encode ())
12- if public_key :
13- self ._public_key = self .load_key (key = public_key .encode ())
7+ class CryptoBase :
8+ @staticmethod
9+ def load_key (key ):
10+ return RSA .importKey (key )
11+
12+ @staticmethod
13+ def _create_cipher (key ):
14+ return PKCS1_OAEP .new (key )
1415
1516 @staticmethod
1617 def to_bytes (serializable : str , encoding = 'UTF-8' ) -> bytes :
@@ -20,26 +21,28 @@ def to_bytes(serializable: str, encoding='UTF-8') -> bytes:
2021 def from_bytes (deserializable : bytes , encoding = 'UTF-8' ) -> str :
2122 return deserializable .decode (encoding = encoding )
2223
23- @staticmethod
24- def to_base_85 (serializable ) -> bytes :
25- return base64 .a85encode (serializable )
2624
27- @staticmethod
28- def from_base_85 (deserializable ) -> bytes :
29- return base64 .a85decode (deserializable )
30-
31- @staticmethod
32- def load_key (key ):
33- return RSA .importKey (key )
34-
35- @staticmethod
36- def _create_cipher (key ):
37- return PKCS1_OAEP .new (key )
25+ class Encoder (CryptoBase ):
26+ def __init__ (self , public_key : str ):
27+ self ._public_key = self .load_key (key = public_key .encode ())
3828
3929 def encrypt_with_public_key (self , unencrypted_text : str ) -> bytes :
4030 cipher = self ._create_cipher (key = self ._public_key )
4131 return cipher .encrypt (message = unencrypted_text .encode ())
4232
33+ @staticmethod
34+ def to_base_85 (serializable ) -> bytes :
35+ return base64 .a85encode (serializable )
36+
37+
38+ class Decoder (CryptoBase ):
39+ def __init__ (self , private_key : str ):
40+ self ._private_key = self .load_key (key = private_key .encode ())
41+
4342 def decrypt_with_private_key (self , encrypted_text : bytes ) -> bytes :
4443 cipher = self ._create_cipher (key = self ._private_key )
4544 return cipher .decrypt (ciphertext = encrypted_text )
45+
46+ @staticmethod
47+ def from_base_85 (deserializable ) -> bytes :
48+ return base64 .a85decode (deserializable )
0 commit comments