Search code examples
python-3.xpycrypto

TypeError when creating a SHA512 hash using pyCryto


Evening All,

I am wanting to verify a a file using Public Key crypto and I cant figure out why I'm getting a Type error for the below code, note 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)

The specific error is:

  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

Solution

  • You're reassigning the name 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)
    

    You should use something like this instead:

    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)
    

    For that reason using generic variable names like f and reusing names for something completely different is discouraged.