From 9cedb879d2128f0c4e8cffa3deb4b34fde91bf9c Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Wed, 28 Oct 2026 20:55:47 -0500 Subject: [PATCH] feat(rsa): implement keypair generation, serialization, and disk persistence - Add generate_rsa_keypair with PKCS#8 private and SPKI public PEM encoding - Enforce minimum 2048-bit key size via KeySizeError guard - Add save_keypair_to_disk setting POSIX permissions (0o600 private, 0o644 public) - Add load_rsa_private_key_pem, and load_rsa_public_key_pem loaders - Add comprehensive unit and rountrips tests --- src/myencrypter/algorithms/rsa.py | 109 ++++++++++++++++++++++++++++++ tests/test_rsa_keys.py | 82 ++++++++++++++++++++++ 2 files changed, 191 insertions(+) create mode 100644 src/myencrypter/algorithms/rsa.py create mode 100644 tests/test_rsa_keys.py diff --git a/src/myencrypter/algorithms/rsa.py b/src/myencrypter/algorithms/rsa.py new file mode 100644 index 0000000..78e4075 --- /dev/null +++ b/src/myencrypter/algorithms/rsa.py @@ -0,0 +1,109 @@ +from dataclasses import dataclass +from pathlib import Path + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa + + +@dataclass(frozen=True) +class RSAKeyPair: + private_bytes: bytes + public_bytes: bytes + key_size_bits: int + + +class KeySizeError(ValueError): + pass + + +def _validate_rsa_key_size(key_size: int) -> int: + if key_size < 2048: + raise KeySizeError(f"Key size must be at least 2048 bits, got {key_size}") + return key_size + + +def generate_rsa_keypair(key_size: int = 2048) -> RSAKeyPair: + + # Guard clause + valid_key_size = _validate_rsa_key_size(key_size) + + """ + 1. Generating the Private Key Object + """ + + private_key = rsa.generate_private_key( + public_exponent=65537, + key_size=valid_key_size, + ) + + """ + 2. Deriving the Public Key + In assymetric cryptography, the public key is mathematically derived + from the private key + """ + + public_key = private_key.public_key() + + """ + 3. Serializing to PEM format + Cryptography keys in memory are mathematical objects; to send or + store them, we serialize them into PEM (Base64/ASCII armor) using + standard formats + """ + + # Private key -> PKCS#8 format (unencrypted for our experiment) + private_bytes = private_key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + + # Public key -> SubjectPublicKeyInfo (SPKI) format + public_bytes = public_key.public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo, + ) + + """ + 4. Return the Dataclass + """ + + # raise NotImplementedError + return RSAKeyPair( + private_bytes=private_bytes, + public_bytes=public_bytes, + key_size_bits=key_size, + ) + + +def save_keypair_to_disk(keypair: RSAKeyPair, key_dest: Path) -> tuple[Path, Path]: + # raise NotImplementedError + priv_path = key_dest + pub_path = Path(f"{key_dest}.pub") + + # 1. Write the private key and restrict permissions to owner-only (0x600) + priv_path.write_bytes(keypair.private_bytes) + priv_path.chmod(0o600) + + # 2. Write the public key and set standard permissions (0o644) + pub_path.write_bytes(keypair.public_bytes) + pub_path.chmod(0o644) + + return priv_path, pub_path + + +def load_rsa_private_key_pem(priv_path: Path) -> rsa.RSAPrivateKey: + # raise NotImplementedError + data = priv_path.read_bytes() + key = serialization.load_pem_private_key(data, password=None) + if not isinstance(key, rsa.RSAPrivateKey): + raise TypeError(f"Expected RSA private key, got {type(key)}") + return key + + +def load_rsa_public_key_pem(pub_path: Path) -> rsa.RSAPublicKey: + data = pub_path.read_bytes() + key = serialization.load_pem_public_key(data) + if not isinstance(key, rsa.RSAPublicKey): + raise TypeError(f"Expected RSA public key, got {type(key)}") + return key diff --git a/tests/test_rsa_keys.py b/tests/test_rsa_keys.py new file mode 100644 index 0000000..4273fea --- /dev/null +++ b/tests/test_rsa_keys.py @@ -0,0 +1,82 @@ +# The Cryptographic Concepts to Implement: +# RSA Key Generations +# - Standard public exponent: e = 65537 +# 0x10001, prime with Fermat property for efficient verification. +# - Key Size: 2048-bit minimum (or 4096-bit) +# PEM Serialization +# - Private Key: +# Stored as PKCS#8 format +# Permissions: 0o600 (rw-------); read/write only by owner +# - Public Key: +# Stored as SubjectPublicKeyInfo (SPKI) format with .pub suffix +# Permissions: 0o664 (rw-r--r--); owner can read/write, others read-only) + + +import stat +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives.asymmetric import rsa + +from myencrypter.algorithms.rsa import ( + RSAKeyPair, + generate_rsa_keypair, + load_rsa_private_key_pem, + load_rsa_public_key_pem, + save_keypair_to_disk, +) + +"""RSA key generation, serialization, and disk persistence tests.""" + + +def test_generate_rsa_keypair_structure() -> None: + """Key generation produces valid PEM-encoded PKCS#8 and SPKI key material.""" + keypair: RSAKeyPair = generate_rsa_keypair(key_size=2048) + + assert isinstance(keypair, RSAKeyPair) + assert keypair.key_size_bits == 2048 + assert keypair.private_bytes.startswith(b"-----BEGIN PRIVATE KEY-----") + assert keypair.private_bytes.strip().endswith(b"-----END PRIVATE KEY-----") + assert keypair.public_bytes.startswith(b"-----BEGIN PUBLIC KEY-----") + assert keypair.public_bytes.strip().endswith(b"-----END PUBLIC KEY-----") + + +def test_generate_rsa_keypair_rejects_insecure_size() -> None: + """Key sizes below 2048 bits should be rejected for safety.""" + + # not really sure how to continue + with pytest.raises(ValueError, match="Key size must be at least 2048 bits"): + generate_rsa_keypair(key_size=1024) + + +def test_save_and_load_keypair_roundtrip(tmp_path: Path) -> None: + """Keys saved to disk must preserve correct file permissions and parse back. + Assertions: + - keys can be written to disk ( and .pub) + - The private key has strict permissions (0o600) + - The public key has standard permissions (0o644) + - Loading the PEM files back into typed key objects (load_rsa_private_key_pem, + load_rsa_public_key_pem) successfully recreates valid RSA keys. + """ + # 1 - instantiate temp path pytest fixture + key_dest = tmp_path / "id_rsa" + + # 2 - call the function to be tested + keypair = generate_rsa_keypair(key_size=2048) + priv_path, pub_path = save_keypair_to_disk(keypair, key_dest) + + assert priv_path == key_dest + assert pub_path == tmp_path / "id_rsa.pub" + assert priv_path.exists() + assert pub_path.exists() + + assert stat.S_IMODE(priv_path.stat().st_mode) == 0o600 + assert stat.S_IMODE(pub_path.stat().st_mode) == 0o644 + + loaded_priv = load_rsa_private_key_pem(priv_path) + loaded_pub = load_rsa_public_key_pem(pub_path) + + assert isinstance(loaded_priv, rsa.RSAPrivateKey) + assert isinstance(loaded_pub, rsa.RSAPublicKey) + assert loaded_priv.key_size == 2048 + assert loaded_pub.key_size == 2048