crypto_api/RSA_Crypto/generate_save.py
2025-03-02 17:58:27 +03:00

105 lines
3.6 KiB
Python

"""
Generate and save RSA key pair
"""
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
class RSAKeyPair:
"""
Class for generating and saving RSA key pair
"""
def __init__(self, private_key_file, public_key_file):
self.private_key_file = private_key_file
self.public_key_file = public_key_file
self.private_key = None
self.public_key = None
def generate_private_key(self):
"""
Generate RSA private key.
The generated key has a 2048 bit length and a public exponent of 65537.
"""
self.private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
def generate_public_key(self):
"""
Generate the public key from the private key.
Raises:
ValueError: Private key must be generated first.
"""
if self.private_key is None:
raise ValueError("Private key must be generated first.")
self.public_key = self.private_key.public_key()
def save_private_key(self):
"""
Save the generated private key to a file.
The private key is saved in PEM format with the Traditional OpenSSL
format and no encryption. If the private key has not been generated yet,
a ValueError is raised.
Raises:
ValueError: Private key must be generated before saving.
"""
if self.private_key is None:
raise ValueError("Private key must be generated before saving.")
with open(self.private_key_file, 'wb') as f:
f.write(self.private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
))
def save_public_key(self):
"""
Save the generated public key to a file.
The public key is saved in PEM format with the SubjectPublicKeyInfo
format. If the public key has not been generated yet, a ValueError is
raised.
Raises:
ValueError: Public key must be generated before saving.
"""
if self.public_key is None:
raise ValueError("Public key must be generated before saving.")
with open(self.public_key_file, 'wb') as f:
f.write(self.public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
))
def generate_and_save_keys(self):
"""
Generate and save the private and public keys to the specified files.
This method first checks if the key files already exist. If not, it
generates the private key and saves it to the private key file, and
generates the public key based on the private key and saves it to the
public key file. If the files already exist, it simply prints a message
to the console.
This method does not raise any exceptions if the files already exist.
"""
if not os.path.exists(self.private_key_file) and not os.path.exists(self.public_key_file):
try:
self.generate_private_key()
self.save_private_key()
self.generate_public_key()
self.save_public_key()
except ValueError as e:
print(e)