9
9
pkcs1_15 ,
10
10
)
11
11
12
+ from libp2p .crypto .exceptions import (
13
+ CryptographyError ,
14
+ )
12
15
from libp2p .crypto .keys import (
13
16
KeyPair ,
14
17
KeyType ,
15
18
PrivateKey ,
16
19
PublicKey ,
17
20
)
18
21
22
+ MAX_RSA_KEY_SIZE = 4096
23
+
24
+
25
+ def validate_rsa_key_size (key : RsaKey ) -> None :
26
+ """
27
+ Validate that an RSA key's size is within acceptable bounds.
28
+
29
+ :param key: The RSA key to validate
30
+ :raises CryptographyError: If the key size exceeds the maximum allowed size
31
+ """
32
+ key_size = key .size_in_bits ()
33
+ if key_size > MAX_RSA_KEY_SIZE :
34
+ msg = f"RSA key size { key_size } "
35
+ msg += f"exceeds maximum allowed size { MAX_RSA_KEY_SIZE } "
36
+ raise CryptographyError (msg )
37
+
19
38
20
39
class RSAPublicKey (PublicKey ):
21
40
def __init__ (self , impl : RsaKey ) -> None :
41
+ validate_rsa_key_size (impl )
22
42
self .impl = impl
23
43
24
44
def to_bytes (self ) -> bytes :
@@ -27,6 +47,7 @@ def to_bytes(self) -> bytes:
27
47
@classmethod
28
48
def from_bytes (cls , key_bytes : bytes ) -> "RSAPublicKey" :
29
49
rsakey = RSA .import_key (key_bytes )
50
+ validate_rsa_key_size (rsakey )
30
51
return cls (rsakey )
31
52
32
53
def get_type (self ) -> KeyType :
@@ -43,10 +64,15 @@ def verify(self, data: bytes, signature: bytes) -> bool:
43
64
44
65
class RSAPrivateKey (PrivateKey ):
45
66
def __init__ (self , impl : RsaKey ) -> None :
67
+ validate_rsa_key_size (impl )
46
68
self .impl = impl
47
69
48
70
@classmethod
49
71
def new (cls , bits : int = 2048 , e : int = 65537 ) -> "RSAPrivateKey" :
72
+ if bits > MAX_RSA_KEY_SIZE :
73
+ msg = f"Requested RSA key size { bits } "
74
+ msg += f"exceeds maximum allowed size { MAX_RSA_KEY_SIZE } "
75
+ raise CryptographyError (msg )
50
76
private_key_impl = RSA .generate (bits , e = e )
51
77
return cls (private_key_impl )
52
78
0 commit comments