Search code examples
pythoncryptographyrsapycryptodome

TypeError: can't concat str to bytes - Python + pycryptodome


I'm receiving a TypeError when trying to encrypt + decrypt a file using pycryptodome. I've looked around but can't find much relevant to pycryptodome regarding this. The error is: Error Image

The code I'm using is:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii



print("Now executing RSA")
# generate the RSA keys and print them on the console (as hex numbers and in the PKCS#8 PEM ASN.1 format)

keyPair = RSA.generate(3072)

pubKey = keyPair.publickey()
print(f"Public key:  (n={hex(pubKey.n)}, e={hex(pubKey.e)})")
pubKeyPEM = pubKey.exportKey()
print(pubKeyPEM.decode('ascii'))

print(f"Private key: (n={hex(pubKey.n)}, d={hex(keyPair.d)})")
privKeyPEM = keyPair.exportKey()
print(privKeyPEM.decode('ascii'))

# encrypt the message using RSA-OAEP encryption scheme (RSA with PKCS#1 OAEP padding) with the RSA public key
# msg = b'A message for encryption'
f = open("plaintext.txt", "r")
f = f.read()
encryptor = PKCS1_OAEP.new(pubKey)
encrypted = encryptor.encrypt(f)
print("Encrypted:", binascii.hexlify(encrypted))

# decrypt the message using RSA-OAEP with the RSA Private key

decryptor = PKCS1_OAEP.new(keyPair)
decrypted = decryptor.decrypt(encrypted)
print('Decrypted:', decrypted)

Solution

  • You need to convert plaintext into bytes or read file as binary data. add b to read file as binary data.

    f = open("plaintext.txt", "rb")
    

    A side note You should consider closing the file after finishing using it

    file = open("plaintext.txt", "rb")
    f = file.read()
    encryptor = PKCS1_OAEP.new(pubKey)
    encrypted = encryptor.encrypt(f)
    print("Encrypted:", binascii.hexlify(encrypted))
    file.close()