Trying to verify SHA1 message signature using Python. What am I doing wrong?
Asked Answered
M

2

11

I'm attempting to verify the SHA1 signature of a message by downloading a certificate from a website and extracting its public key. There's a few bits of sample code elsewhere on SO (here and here), however I haven't yet figured out what I'm doing wrong.

import requests
from M2Crypto import BIO, RSA, EVP, X509

def verify_message(cert_url, msg, sig):
    cert_text = requests.get(cert_url, verify=True)
    cert = X509.load_cert_string(cert_text.content)
    pubkey = cert.get_pubkey()
    sig = sig.decode('base64')

    # Write a few files to disk for debugging purposes
    f = open("sig", "wb")
    f.write(sig)
    f.close()

    f = open("msg", "w")
    f.write(msg)
    f.close()

    f = open("mypubkey.pem", "w")
    f.write(pubkey.get_rsa().as_pem())
    f.close()

    pubkey.reset_context(md='sha1')
    pubkey.verify_init()
    pubkey.verify_update(msg)
    assert pubkey.verify_final(sig) == 1

This gives me the following assertion error:

  File "/tmp/test.py", line 71, in verify_message
    assert pubkey.verify_final(sig) == 1
AssertionError

However, if I use openssl from the command line along with the files generated from the above Python script, it works fine:

[jamie@test5 tmp]$ openssl dgst -sha1 -verify mypubkey.pem -signature sig msg
Verified OK

I've hit a brick wall here; any suggestions would be greatly appreciated. Thanks!

Moxa answered 3/3, 2013 at 15:56 Comment(3)
why do you believe you need to base64 decode the signature?Hydrozoan
@GregS Thanks for the reply. The signature is transmitted via a HTTP POST along with the message itself; it's base64 encoded when I get it. I omitted that step for clarity.Moxa
This works fine for me on Ubuntu with openssl 1.0.1 and m2crypto 0.21.1. What versions are you working with?Bihari
E
5

Your code is work properly — https://gist.github.com/kalloc/5106808 I see something else wrong here

Evert answered 7/3, 2013 at 9:49 Comment(0)
O
1

This code is working perfectly fine at my end.

Oviparous answered 12/3, 2013 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.