簡體   English   中英

類型錯誤:無法將 str 連接到字節 - Python + pycryptodome

[英]TypeError: can't concat str to bytes - Python + 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 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()

確保兩種數據類型相同。 您可以嘗試將文本文件轉換為字節,以便數據類型相等,因此可以連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM