Python cryptography module public_key verify() method

3.1k Views Asked by At

I'm on python 3.8.5, using cryptography 2.9.2. I need to verify a digital signature from a public key, but I'm very confused about the padding class in cryptography.

The public keys and signatures are sent to me in an XML file. Using LXML, I load the file into the variable inxml and get those items with this code. This code works.

message = inxml.findall('//message).text #The message that was signed.
user-key = inxml.findall('//pubkey')[0].text #The text file ---BEGIN PUBLIC KEY--- and so on.
c=bytes(user0key.encode()) #Convert the string to a bytes object.
user-key = serialization.load_pem_public_key(c, backend=default_backend()) #Use the py-cryptography method to make a public-key object.
user-sig = inxml.findall('//signature')[0].text #Get the base64-encoded signature.
user-sig = base64.b64decode(user-sig) #Decode the signature back to binary. 

This gives me:

  • message as a string
  • user-key as type public_key
  • user-sig as bytes.

The next line of code gives me an error:

user-key.verify(user-sig, message, padding.PKCS7(128), hashes.SHA512)

The error I get is:

Expected instance of hashes.HashAlgorithm

The person who made the XML file created the signature with these commands (in Powershell): ./openssl.exe dgst -sha512 -sign $private-key -passin pass:$password -out sig.sig $message ./openssl.exe base64 -in sig.sig -out $base64

The $base64 variable was then put into the XML file.

I don't understand why using hashes.SHA512 should cause an error. And I really don't understand the padding argument at all. Can someone point me in the right direction?

1

There are 1 best solutions below

0
On BEST ANSWER

You have two issues here. Assuming you're calling RSAPublicKey.verify the documentation notes that padding needs to be an instance of AsymmetricPadding, and not a symmetric padding instance. Since this is a signature there are two possible paddings that may be in use: PSS or PKCS1v15. It would be useful to find out which one it should be, but you can also just try PKCS1v15 (which it likely is) and see if it works.

The other problem you have is that this method requires an instance of the hash, not the bare class. In other words, you should be passing hashes.SHA512(), not hashes.SHA512.