Use Python PyCrypto module to sign and verify an MD5 digest 

Joined:
04/09/2007
Posts:
784

October 12, 2013 13:20:34    Last update: November 01, 2013 10:35:58
>>> import Crypto.PublicKey.RSA as RSA
>>> key = RSA.importKey(open('mykey').read())
>>> sig = key.sign('a6385c1250835d65fb2bd1ae55250f3b', 123)
>>> key.verify('a6385c1250835d65fb2bd1ae55250f3b', sig)
True
>>> pubkey = RSA.importKey(open('mykey.pem.pub').read())
>>> pubkey.verify('a6385c1250835d65fb2bd1ae55250f3b', sig)
True


The signature can be verified with either the private or the public key. For RSA, the second parameter to key.sign does not matter, key.sign('a6385c1250835d65fb2bd1ae55250f3b', 1) would have generated exactly the same signature.

Update: signature created with above method is discouraged by the PyCrypto author. The generated signature is not compatible with Java. Use this method to create a Java compatible signature:
>>> from Crypto.PublicKey import RSA
>>> from Crypto.Signature import PKCS1_v1_5
>>> from Crypto.Hash import SHA256
>>> key = RSA.importKey(open('mykey').read())
>>> h = SHA256.new()
>>> h.update('The message to sign')
>>> signer = PKCS1_v1_5.new(key)
>>> sig = signer.sign(h)
>>> sig.encode('hex')

Share |
| Comment  | Tags