How can I keep the private and publish key for later use? Since the program always generates different keys?

Asked

Viewed 330 times

0

Well, I wish I could save the private key and publish it to use later to encrypt and if someone wants to decrypt my message, but every time the program generates a new key. How can I save the keys and then use it later to encrypt or decrypt?

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import de

#gerando chave provada
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)

#gerando chave publica
public_key = private_key.public_key()

#Entrada do texto
mensagem = str(input("escreva uma mensagem:"))
bytes_mensagem = mensagem.encode('utf-8')

#Criptografando o texto
texto_cifrado = public_key.encrypt(
    bytes_mensagem,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA1()),
        algorithm=hashes.SHA1(),
        label=None
    )
)
print(texto_cifrado)

# Descriptografando o texto
texto_descriptografado = private_key.decrypt(
    texto_cifrado,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA1()),
        algorithm=hashes.SHA1(),
        label=None
    )

)
print(texto_descriptografado)

1 answer

1


Extract bytes to be saved from your private key:

binary_data = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,           # codificacao
    format=serialization.PrivateFormat.PKCS8,          # formato
    encryption_algorithm=serialization.NoEncryption(), # para criptografar a chave
)

Save them to a binary file:

with open('minha_chave.rsa.key', 'wb') as f:
    f.write(binary_data)

Then to read the key again, just do the reverse, open the file and read the bytes of it:

with open('minha_chave.rsa.key', 'rb') as f:
    binary_data = f.read()
private_key = serialization.load_pem_private_key(
    binary_data, password=None, backend=default_backend())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.