类型错误:can';t concat str to bytes-Python+;隐窝

类型错误:can';t concat str to bytes-Python+;隐窝,python,cryptography,rsa,pycryptodome,Python,Cryptography,Rsa,Pycryptodome,尝试使用pycryptodome对文件进行加密和解密时,我收到一个TypeError。我环顾四周,但找不到与pycryptodome有关的内容。错误是: 我使用的代码是: from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP import binascii print("Now executing RSA") # generate the RSA keys and print the

尝试使用pycryptodome对文件进行加密和解密时,我收到一个TypeError。我环顾四周,但找不到与pycryptodome有关的内容。错误是:

我使用的代码是:

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)

您需要将明文转换为字节或将文件作为二进制数据读取。添加
b
以将文件作为二进制数据读取

f = open("plaintext.txt", "rb")
请注意在使用文件

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

确保两种数据类型相同。您可以尝试将文本文件转换为字节,以便数据类型相等,从而可以连接