Python verifying digital signature with payload and public key string

I have a piece of data ['payload'] that is Base64 encoded. Then I have a “signature” that contains the signature of the payload. I have a public key. Signature Algorithm - SHA512wRSA

How to authenticate data in Python? I use the following code to verify, but it does not seem to work

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"
+3
source share
1 answer

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

  • two different versions of SHA512 are imported;
  • 64, 64 _ (, base-64-url);
  • signature_algorithm keytype ;
  • key PSS;
  • m.hexdigest() ;
  • SHA512.new(rsakey);
  • , , SHA512 ;

PSS. , , , . , , , .

from Crypto.Signature import PKCS1_PSS
from Crypto.Hash import SHA512
from Crypto.PublicKey import RSA
from Crypto import Random
message = 'To be signed'
key = RSA.importKey(open('privkey.der').read())
h = SHA512.new()
h.update(message)
signer = PKCS1_PSS.new(key)
signature = PKCS1_PSS.sign(h)

, PSS , , , , , MGF1 , , ...

0

Source: https://habr.com/ru/post/1680747/


All Articles