rufuse large RSA keys

This commit is contained in:
Khwahish Patel
2025-03-05 12:29:52 +05:30
committed by Paul Robinson
parent 7d324b129b
commit e150d3153a

View File

@ -9,6 +9,9 @@ from Crypto.Signature import (
pkcs1_15,
)
from libp2p.crypto.exceptions import (
CryptographyError,
)
from libp2p.crypto.keys import (
KeyPair,
KeyType,
@ -16,9 +19,26 @@ from libp2p.crypto.keys import (
PublicKey,
)
MAX_RSA_KEY_SIZE = 4096
def validate_rsa_key_size(key: RsaKey) -> None:
"""
Validate that an RSA key's size is within acceptable bounds.
:param key: The RSA key to validate
:raises CryptographyError: If the key size exceeds the maximum allowed size
"""
key_size = key.size_in_bits()
if key_size > MAX_RSA_KEY_SIZE:
msg = f"RSA key size {key_size} "
msg += f"exceeds maximum allowed size {MAX_RSA_KEY_SIZE}"
raise CryptographyError(msg)
class RSAPublicKey(PublicKey):
def __init__(self, impl: RsaKey) -> None:
validate_rsa_key_size(impl)
self.impl = impl
def to_bytes(self) -> bytes:
@ -27,6 +47,7 @@ class RSAPublicKey(PublicKey):
@classmethod
def from_bytes(cls, key_bytes: bytes) -> "RSAPublicKey":
rsakey = RSA.import_key(key_bytes)
validate_rsa_key_size(rsakey)
return cls(rsakey)
def get_type(self) -> KeyType:
@ -43,10 +64,15 @@ class RSAPublicKey(PublicKey):
class RSAPrivateKey(PrivateKey):
def __init__(self, impl: RsaKey) -> None:
validate_rsa_key_size(impl)
self.impl = impl
@classmethod
def new(cls, bits: int = 2048, e: int = 65537) -> "RSAPrivateKey":
if bits > MAX_RSA_KEY_SIZE:
msg = f"Requested RSA key size {bits} "
msg += f"exceeds maximum allowed size {MAX_RSA_KEY_SIZE}"
raise CryptographyError(msg)
private_key_impl = RSA.generate(bits, e=e)
return cls(private_key_impl)