'python verifying a digital signature with a payload and public key string

I have a piece of data [ 'payload' ] which is Base64 encoded. Then i have a 'signature' which contains the payload's signature. I have a public key. The signature algorithm is SHA512withRSA

How can I verify the authenticity of the data in Python ? I am using the following code to check, but it doesn't seem to be working

import base64
import hashlib
from Crypto.PublicKey import RSA 
from Crypto.Signature import SHA512
from Crypto.Hash import SHA512 
from base64 import b64decode 

# Public Key
key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEpFwIarbm48m6ueG+jhpt2vCGaqXZlwR/HPuL4zH1DQ/eWFbgQtVnrta8QhQz3ywLnbX6s7aecxUzzNJsTtS8VxKAYll4E1lJUqrNdWt8CU+TaUQuFm8vzLoPiYKEXl4bX5rzMQUMqA228gWuYmRFQnpduQTgnYIMO8XVUQXl5wIDAQAB"

# Base64 Encoded payload
payload = "some_string_payload"
decoded_payload = base64.b64decode(payload)

signature = "gw5K+WvO43673XBinZOmwgrZ3ttVuZ17/7SBnzqAAD4pgiwzYbZuEwn2lev6FW01f6TL0d9cNH4WtT53bQnTlhLQOZi4mHTTtM64O7MNljSA5zjJTUl77wXK/cJM+/G6R4YgYAnjydXAZjbMKY4Z9kV0qz2spdnS7Je7Q8I1xaU="
signature_algorithm = "SHA512withRSA"
keytype = "RSA"


m = hashlib.sha512()
m.update( key )
m.update( decoded_payload )
print m
m.hexdigest()
print m


keyDER = b64decode(key)
rsakey = RSA.importKey(keyDER)

signer = SHA512.new(rsakey) 

if signer.verify(m, b64decode(signature)):
    print "Verified"
else:
    print "Not Verified"


Solution 1:[1]

The code in the question has a couple of mistakes, in order of appearance:

  • there are two different SHA512 implementations imported;
  • the payload is clearly not base 64 encoded, normal base 64 doesn't represent text nor does it contain _ characters (base-64-url however does);
  • the signature_algorithm and keytype variables are not even used;
  • the key should not be hashed to implement a normal PSS signature scheme;
  • the result of m.hexdigest() is ignored;
  • you cannot generate a signature generation class by SHA512.new(rsakey);

As indicated your code doesn't even compile, because SHA512 class cannot sign;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1