How can I encrypt a user input text? giving error

Asked

Viewed 353 times

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)
  • Nathalia where is the error? Please post the LOG to make it easier to help

  • hello, when I put message = b'what will be encrypted it right'

  • but when I put the text as message = str(input("write a message:"))

2 answers

1


Cryptography only works with bytes. That’s what the lyrics mean b at the beginning of the literal. When reading a user string it comes to str, and you need to convert to bytes in order to encrypt.

To do this encoding use the method encode() passing an encoding (the most common is the utf-8 that can encode all Unicode characters, without spending too 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)

1

Your question has already been answered, but this part 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;

for:

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 you don’t need that code.

if senha_cripto == 'batata':
    break;

Simply because, it’s not an infinite loop while(True), because it will be stopped just when you hit the password.

Browser other questions tagged

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