crypto/RSA_Crypto/decrypt.py

87 lines
2.4 KiB
Python

"""
Decrypts messages encrypted with RSA.
"""
import base64
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
class RSADecryptor:
"""
Module for decrypting messages encrypted with RSA.
Provides
--------
* :class:`RSADecryptor` - class for decrypting messages.
"""
def __init__(self, private_key_file):
"""
Initialize an RSADecryptor with a file containing a private RSA key.
Parameters
----------
private_key_file : str
The path to the private key file, which should be in PEM format.
Attributes
----------
private_key_file : str
The path to the private key file, which should be in PEM format.
private_key : cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey
The loaded private key.
"""
self.private_key_file = private_key_file
self.private_key = self.load_private_key()
def load_private_key(self):
"""
Load a private key from a file.
The file should be in PEM format and contain the private key.
Returns
-------
private_key : cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey
The loaded private key.
"""
with open(self.private_key_file, 'rb') as f:
private_key_data = f.read()
private_key = serialization.load_pem_private_key(
private_key_data,
password=None,
backend=default_backend()
)
return private_key
def decrypt_message(self, encrypted_message):
"""
Decrypt an encrypted message.
Parameters
----------
encrypted_message : str
The encrypted message as a base64 encoded string.
Returns
-------
decrypted_message : str
The decrypted message as a string.
"""
encrypted_bytes = base64.b64decode(encrypted_message)
try:
decrypted = self.private_key.decrypt(
encrypted_bytes,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return decrypted.decode()
except ValueError:
return None