Compare commits
2
Commits
b7d304ba6f
...
432b9cd70c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
432b9cd70c | ||
|
|
c96958221c |
No files matched your search
@@ -1,10 +1,39 @@
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
from cryptography.hazmat.primitives import hashes, serialization
|
from cryptography.hazmat.primitives import hashes, serialization
|
||||||
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
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)
|
@dataclass(frozen=True)
|
||||||
class RSAKeyPair:
|
class RSAKeyPair:
|
||||||
private_bytes: bytes
|
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:
|
def generate_rsa_keypair(key_size: int = 2048) -> RSAKeyPair:
|
||||||
|
"""Generate a new RSA private/public key pair."""
|
||||||
# Guard clause
|
|
||||||
valid_key_size = _validate_rsa_key_size(key_size)
|
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
|
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."""
|
"""Encrypt plaintext bytes using RSA-OAEP with SHA-256."""
|
||||||
return public_key.encrypt(
|
|
||||||
plaintext=plaintext,
|
cfg = config if config is not None else RSAConfig()
|
||||||
padding=padding.OAEP(
|
pad = cfg.build_padding()
|
||||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
|
||||||
algorithm=hashes.SHA256(),
|
return public_key.encrypt(plaintext=plaintext, padding=pad)
|
||||||
label=None,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
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."""
|
"""Decrypt ciphertext bytes using RSA-OAEP with SHA-256."""
|
||||||
|
|
||||||
|
cfg = config if config is not None else RSAConfig()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
return private_key.decrypt(
|
pad = cfg.build_padding()
|
||||||
ciphertext=ciphertext,
|
return private_key.decrypt(ciphertext=ciphertext, padding=pad)
|
||||||
padding=padding.OAEP(
|
|
||||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
|
||||||
algorithm=hashes.SHA256(),
|
|
||||||
label=None,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise DecryptionError("Failed to decrypt with RSA: invalid padding") from exc
|
raise DecryptionError("Failed to decrypt with RSA: invalid padding") from exc
|
||||||
@@ -1,15 +1,23 @@
|
|||||||
import pytest
|
import pytest
|
||||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
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:
|
def _generate_private_key() -> rsa.RSAPrivateKey:
|
||||||
private_key = rsa.generate_private_key(
|
return rsa.generate_private_key(
|
||||||
public_exponent=65537,
|
public_exponent=65537,
|
||||||
key_size=2048,
|
key_size=2048,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_rsa_encryption_decryption() -> None:
|
||||||
|
private_key = _generate_private_key()
|
||||||
public_key = private_key.public_key()
|
public_key = private_key.public_key()
|
||||||
|
|
||||||
message: bytes = b"Hello, from kiskaadee!"
|
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:
|
def test_rsa_decryption_with_wrong_key_fails() -> None:
|
||||||
private_key = rsa.generate_private_key(
|
private_key = _generate_private_key()
|
||||||
public_exponent=65537,
|
wrong_private_key = _generate_private_key()
|
||||||
key_size=2048,
|
|
||||||
)
|
|
||||||
|
|
||||||
wrong_private_key = rsa.generate_private_key(
|
|
||||||
public_exponent=65537,
|
|
||||||
key_size=2048,
|
|
||||||
)
|
|
||||||
|
|
||||||
public_key = private_key.public_key()
|
public_key = private_key.public_key()
|
||||||
|
|
||||||
message: bytes = b"Hello, from kiskaadee!"
|
message: bytes = b"Hello, from kiskaadee!"
|
||||||
@@ -39,3 +39,83 @@ def test_rsa_decryption_with_wrong_key_fails() -> None:
|
|||||||
assert isinstance(ciphertext, bytes)
|
assert isinstance(ciphertext, bytes)
|
||||||
with pytest.raises(DecryptionError):
|
with pytest.raises(DecryptionError):
|
||||||
decrypt_rsa(wrong_private_key, ciphertext)
|
decrypt_rsa(wrong_private_key, ciphertext)
|
||||||
|
|
||||||
|
|
||||||
|
def test_rsa_encryption_same_message_produces_different_ciphertext() -> None:
|
||||||
|
private_key = _generate_private_key()
|
||||||
|
public_key = private_key.public_key()
|
||||||
|
|
||||||
|
message: bytes = b"Hello, from kiskaadee!"
|
||||||
|
ciphertext1: bytes = encrypt_rsa(public_key, message)
|
||||||
|
ciphertext2: bytes = encrypt_rsa(public_key, message)
|
||||||
|
|
||||||
|
assert isinstance(ciphertext1, bytes)
|
||||||
|
assert isinstance(ciphertext2, bytes)
|
||||||
|
assert ciphertext1 != ciphertext2
|
||||||
|
assert decrypt_rsa(private_key, ciphertext1) == message
|
||||||
|
assert decrypt_rsa(private_key, ciphertext2) == message
|
||||||
|
|
||||||
|
|
||||||
|
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[-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