feat(rsa): support configurable padding schemes and hash algorithms
- introduce `RSAConfig` dataclass supporting OAEP and PKCS#1 v1.5 padding - update `encrypt_rsa` and `decrypt_rsa` to accept optional configuration - refactor test helper `_generate_private_key` for RSA test suite - add tests verifying PKCS#1 v1.5 tampering and decryption behavior
This commit is contained in:
1 parent
c96958221c
commit
432b9cd70c
2 files changed
+112
-44
No files matched your search
@@ -1,10 +1,39 @@
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RSAConfig:
|
||||
"""Configuration for RSA encryption/decryption."""
|
||||
|
||||
padding_scheme: Literal["oaep", "pkcs1v15"] = "oaep"
|
||||
hash_algorithm: Literal["sha256", "sha512"] = "sha256"
|
||||
label: bytes | None = None
|
||||
|
||||
def build_padding(self) -> padding.AsymmetricPadding:
|
||||
"""Translate string attributes to cryptography library padding objects."""
|
||||
if self.padding_scheme == "oaep":
|
||||
hash_map = {
|
||||
"sha256": hashes.SHA256(),
|
||||
"sha512": hashes.SHA512(),
|
||||
}
|
||||
selected_hash = hash_map[self.hash_algorithm]
|
||||
return padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=selected_hash),
|
||||
algorithm=selected_hash,
|
||||
label=self.label,
|
||||
)
|
||||
|
||||
elif self.padding_scheme == "pkcs1v15":
|
||||
return padding.PKCS1v15()
|
||||
|
||||
raise ValueError(f"Unsupported padding scheme: {self.padding_scheme}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RSAKeyPair:
|
||||
private_bytes: bytes
|
||||
@@ -27,8 +56,7 @@ def _validate_rsa_key_size(key_size: int) -> int:
|
||||
|
||||
|
||||
def generate_rsa_keypair(key_size: int = 2048) -> RSAKeyPair:
|
||||
|
||||
# Guard clause
|
||||
"""Generate a new RSA private/public key pair."""
|
||||
valid_key_size = _validate_rsa_key_size(key_size)
|
||||
|
||||
"""
|
||||
@@ -113,28 +141,26 @@ def load_rsa_public_key_pem(pub_path: Path) -> rsa.RSAPublicKey:
|
||||
return key
|
||||
|
||||
|
||||
def encrypt_rsa(public_key: rsa.RSAPublicKey, plaintext: bytes) -> bytes:
|
||||
def encrypt_rsa(
|
||||
public_key: rsa.RSAPublicKey, plaintext: bytes, config: RSAConfig | None = None
|
||||
) -> bytes:
|
||||
"""Encrypt plaintext bytes using RSA-OAEP with SHA-256."""
|
||||
return public_key.encrypt(
|
||||
plaintext=plaintext,
|
||||
padding=padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(),
|
||||
label=None,
|
||||
),
|
||||
)
|
||||
|
||||
cfg = config if config is not None else RSAConfig()
|
||||
pad = cfg.build_padding()
|
||||
|
||||
return public_key.encrypt(plaintext=plaintext, padding=pad)
|
||||
|
||||
|
||||
def decrypt_rsa(private_key: rsa.RSAPrivateKey, ciphertext: bytes) -> bytes:
|
||||
def decrypt_rsa(
|
||||
private_key: rsa.RSAPrivateKey, ciphertext: bytes, config: RSAConfig | None = None
|
||||
) -> bytes:
|
||||
"""Decrypt ciphertext bytes using RSA-OAEP with SHA-256."""
|
||||
|
||||
cfg = config if config is not None else RSAConfig()
|
||||
|
||||
try:
|
||||
return private_key.decrypt(
|
||||
ciphertext=ciphertext,
|
||||
padding=padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(),
|
||||
label=None,
|
||||
),
|
||||
)
|
||||
pad = cfg.build_padding()
|
||||
return private_key.decrypt(ciphertext=ciphertext, padding=pad)
|
||||
except ValueError as exc:
|
||||
raise DecryptionError("Failed to decrypt with RSA: invalid padding") from exc
|
||||
@@ -1,15 +1,23 @@
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
|
||||
from myencrypter.algorithms.rsa import DecryptionError, decrypt_rsa, encrypt_rsa
|
||||
from myencrypter.algorithms.rsa import (
|
||||
DecryptionError,
|
||||
RSAConfig,
|
||||
decrypt_rsa,
|
||||
encrypt_rsa,
|
||||
)
|
||||
|
||||
|
||||
def test_rsa_encryption_decryption() -> None:
|
||||
private_key = rsa.generate_private_key(
|
||||
def _generate_private_key() -> rsa.RSAPrivateKey:
|
||||
return rsa.generate_private_key(
|
||||
public_exponent=65537,
|
||||
key_size=2048,
|
||||
)
|
||||
|
||||
|
||||
def test_rsa_encryption_decryption() -> None:
|
||||
private_key = _generate_private_key()
|
||||
public_key = private_key.public_key()
|
||||
|
||||
message: bytes = b"Hello, from kiskaadee!"
|
||||
@@ -21,16 +29,8 @@ def test_rsa_encryption_decryption() -> None:
|
||||
|
||||
|
||||
def test_rsa_decryption_with_wrong_key_fails() -> None:
|
||||
private_key = rsa.generate_private_key(
|
||||
public_exponent=65537,
|
||||
key_size=2048,
|
||||
)
|
||||
|
||||
wrong_private_key = rsa.generate_private_key(
|
||||
public_exponent=65537,
|
||||
key_size=2048,
|
||||
)
|
||||
|
||||
private_key = _generate_private_key()
|
||||
wrong_private_key = _generate_private_key()
|
||||
public_key = private_key.public_key()
|
||||
|
||||
message: bytes = b"Hello, from kiskaadee!"
|
||||
@@ -42,11 +42,7 @@ def test_rsa_decryption_with_wrong_key_fails() -> None:
|
||||
|
||||
|
||||
def test_rsa_encryption_same_message_produces_different_ciphertext() -> None:
|
||||
private_key = rsa.generate_private_key(
|
||||
public_exponent=65537,
|
||||
key_size=2048,
|
||||
)
|
||||
|
||||
private_key = _generate_private_key()
|
||||
public_key = private_key.public_key()
|
||||
|
||||
message: bytes = b"Hello, from kiskaadee!"
|
||||
@@ -60,20 +56,66 @@ def test_rsa_encryption_same_message_produces_different_ciphertext() -> None:
|
||||
assert decrypt_rsa(private_key, ciphertext2) == message
|
||||
|
||||
|
||||
def test_tampered_ciphertext_raises_decryption_error() -> None:
|
||||
private_key = rsa.generate_private_key(
|
||||
public_exponent=65537,
|
||||
key_size=2048,
|
||||
)
|
||||
def test_oaep_tampered_ciphertext_raises_decryption_error() -> None:
|
||||
"""Configuration implicitly falls to OAEP default"""
|
||||
|
||||
private_key = _generate_private_key()
|
||||
public_key = private_key.public_key()
|
||||
|
||||
message: bytes = b"Alice message is top secret!"
|
||||
ciphertext: bytes = encrypt_rsa(public_key, message)
|
||||
|
||||
ciphertext_array = bytearray(ciphertext)
|
||||
ciphertext_array[0] ^= 0xFF
|
||||
ciphertext_array[-1] ^= 0xFF
|
||||
corrupted_ciphertext: bytes = bytes(ciphertext_array)
|
||||
|
||||
with pytest.raises(DecryptionError):
|
||||
decrypt_rsa(private_key, corrupted_ciphertext)
|
||||
|
||||
|
||||
def test_pkcs1_tampered_ciphertext_implicitly_reject_tampered_message() -> None:
|
||||
"""PCKS implementation should not raise a Value Error
|
||||
Expected: Implicit rejection (silent synthetic return)
|
||||
"""
|
||||
private_key = _generate_private_key()
|
||||
custom_config = RSAConfig(padding_scheme="pkcs1v15")
|
||||
public_key = private_key.public_key()
|
||||
|
||||
message: bytes = b"Shinigami loves apples!"
|
||||
ciphertext: bytes = encrypt_rsa(public_key, message, custom_config)
|
||||
|
||||
# Tamper with the least significant byte instead of the most significant one
|
||||
ciphertext_array = bytearray(ciphertext)
|
||||
ciphertext_array[-1] ^= 0xFF
|
||||
corrupted_ciphertext: bytes = bytes(ciphertext_array)
|
||||
|
||||
recovered = decrypt_rsa(private_key, corrupted_ciphertext, custom_config)
|
||||
|
||||
assert isinstance(recovered, bytes)
|
||||
assert recovered != message
|
||||
|
||||
|
||||
def test_pkcs1_wrong_key_decryption_implicitly_rejected() -> None:
|
||||
"""Expected: Implicit rejection (silent synthetic return)"""
|
||||
private_key = _generate_private_key()
|
||||
public_key = private_key.public_key()
|
||||
|
||||
custom_config = RSAConfig(padding_scheme="pkcs1v15")
|
||||
message: bytes = b"Shinigami loves apples!"
|
||||
ciphertext: bytes = encrypt_rsa(public_key, message, custom_config)
|
||||
recovered = decrypt_rsa(private_key, ciphertext, custom_config)
|
||||
assert isinstance(recovered, bytes)
|
||||
assert recovered == message
|
||||
|
||||
wrong_private_key = _generate_private_key()
|
||||
try:
|
||||
recovered_wrong = decrypt_rsa(
|
||||
wrong_private_key,
|
||||
ciphertext,
|
||||
custom_config,
|
||||
)
|
||||
assert isinstance(recovered_wrong, bytes)
|
||||
assert recovered_wrong != message
|
||||
|
||||
except DecryptionError:
|
||||
pass
|
||||
Reference in new issue
Block a user