def save_key_to_file(key, filename):
# Check if the key is a private key
if isinstance(key, rsa.RSAPrivateKey):
# Serialize the private key in PEM format with PKCS8
pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
else:
# Serialize the public key in PEM format
pem = key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
# Write the serialized key to a file using binary. use [.pem] file extension
with open(filename, 'wb') as file:
file.write(pem)
def load_private_key_from_file(filename):
# read the saved pem file in the pem variable
with open(filename, 'wb') as file:
pem = file.read()
## line 1
## line 2
private_key = serialization.load_pem_private_key(
pem,
password=None,
backend=default_backend()
)
return private_key
def load_public_key_from_file(filename):
# read the saved pem file in the pem variable
with open(filename, 'wb') as file:
pem = file.read()
## line 1
## line 2
public_key = serialization.load_pem_public_key(
pem,
backend=default_backend()
)
return public_key
private_key, public_key = generate_keys()
save_key_to_file(private_key,"private_rsa.pem")
save_key_to_file(public_key,"public_rsa.pem")