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

0

Well, I would like to be able to 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)
    
asked by anonymous 25.10.2018 / 07:41

1 answer

1

Extract the 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 its bytes:

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())
    
26.10.2018 / 15:09