How can I encrypt an input text by the user?

0
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

#gerando a chave privada
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)
#gerando chave publica
public_key = private_key.public_key()

senha_cripto = str(input("Senha para criptografar:")).strip()

while senha_cripto != 'batata':
    print("Senha incorreta, tente novamente!")
    senha_cripto = str(input("Senha para criptografar:")).strip()
    if senha_cripto == 'batata':
        break;

mensagem = str(input("escreva uma mensagem:"))




texto_cifrado = public_key.encrypt(
    mensagem,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA1()),
        algorithm=hashes.SHA1(),
        label=None
    )
)
print(texto_cifrado)


normaltext = private_key.decrypt(
    mensagem,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA1()),
        algorithm=hashes.SHA1(),
        label=None
    )
)

print(normaltext)
    
asked by anonymous 19.10.2018 / 22:06

2 answers

1

Encryption only works with bytes . This is what the letter b means at the beginning of the literal. When reading a user string it comes in str , and you need to convert to bytes to be able to encrypt.

To do this encoding, use the encode() method by passing an encoding (the most common is utf-8 that can encode all unicode characters without spending much space):

mensagem = input("escreva uma mensagem:")
bytes_mensagem = mensagem.encode('utf-8') 
...
texto_cifrado = public_key.encrypt(bytes_mensagem, ...)

Similarly, after encrypting the library will return you bytes. You need to decode the string back:

bytes_mensagem = private_key.decrypt(....)
normaltext = bytes_mensage.decode('utf-8')
print(normaltext)
    
20.10.2018 / 03:47
1

Your question has already been answered, but this snippet of your code can be improved.

while senha_cripto != 'batata':
    print("Senha incorreta, tente novamente!")
    senha_cripto = str(input("Senha para criptografar:")).strip()
    if senha_cripto == 'batata':
        break;

To:

from hashlib import sha256
while sha256(senha_cripto.encode()).hexdigest() != 'f4610aa514477222afac2b77f971d069780ca2846f375849f3dfa3c0047ebbd1':
    print("Senha incorreta, tente novamente!")
    senha_cripto = str(input("Senha para criptografar:")).strip()

And do not presse this code.

if senha_cripto == 'batata':
    break;

Simply because, it is not an infinite loop while(True) , because it will be interrupted as soon as you hit the password.

    
21.10.2018 / 16:49