Skip to content

Commit e150d31

Browse files
Khwahish29pacrob
authored andcommitted
rufuse large RSA keys
1 parent 7d324b1 commit e150d31

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

libp2p/crypto/rsa.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,36 @@
99
pkcs1_15,
1010
)
1111

12+
from libp2p.crypto.exceptions import (
13+
CryptographyError,
14+
)
1215
from libp2p.crypto.keys import (
1316
KeyPair,
1417
KeyType,
1518
PrivateKey,
1619
PublicKey,
1720
)
1821

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+
1938

2039
class RSAPublicKey(PublicKey):
2140
def __init__(self, impl: RsaKey) -> None:
41+
validate_rsa_key_size(impl)
2242
self.impl = impl
2343

2444
def to_bytes(self) -> bytes:
@@ -27,6 +47,7 @@ def to_bytes(self) -> bytes:
2747
@classmethod
2848
def from_bytes(cls, key_bytes: bytes) -> "RSAPublicKey":
2949
rsakey = RSA.import_key(key_bytes)
50+
validate_rsa_key_size(rsakey)
3051
return cls(rsakey)
3152

3253
def get_type(self) -> KeyType:
@@ -43,10 +64,15 @@ def verify(self, data: bytes, signature: bytes) -> bool:
4364

4465
class RSAPrivateKey(PrivateKey):
4566
def __init__(self, impl: RsaKey) -> None:
67+
validate_rsa_key_size(impl)
4668
self.impl = impl
4769

4870
@classmethod
4971
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)
5076
private_key_impl = RSA.generate(bits, e=e)
5177
return cls(private_key_impl)
5278

0 commit comments

Comments
 (0)