使用 pyCryto 创建 SHA512 哈希时出现 TypeError

TypeError when creating a SHA512 hash using pyCryto

晚安,

我想使用 Public 密钥加密来验证一个文件,但我无法弄清楚为什么我会收到以下代码的类型错误,请注意 signatureLength = 512

signature = f[:signatureLength]
f = open('lib/publicKey.pem','rb')
publicKey = RSA.importKey(f.read())
hash = SHA512.new(f[signatureLength:])
verification = PKCS1_PSS.new(publicKey)

具体错误为:

  File "C:\Users\Zach Newton\Desktop\pp\lib\files.py", line 77, in verify_file
    hash = SHA512.new(f[signatureLength:])
TypeError: '_io.BufferedReader' object is not subscriptable

您正在重新分配名称 f:

signature = f[:signatureLength]
f = open('lib/publicKey.pem','rb')
publicKey = RSA.importKey(f.read())
hash = SHA512.new(f[signatureLength:]) # <-- this isn't the same f anymore
verification = PKCS1_PSS.new(publicKey)

你应该改用这样的东西:

signature = f[:signatureLength]
with open('lib/publicKey.pem','rb') as pubkeyfile:
    publicKey = RSA.importKey(pubkeyfile.read())
hash = SHA512.new(signature)
verification = PKCS1_PSS.new(publicKey)

出于这个原因,不鼓励使用像 f 这样的通用变量名称,也不鼓励将名称重复用于完全不同的东西。