Sunday, January 9, 2011

Fun with M2Crypto

Here is one way to load an RSA public key from a string with M2Crypto in python.

from M2Crypto import RSA, BIO

def _load_pub_key(ks):
ks = ks.encode('utf-8')
return RSA.load_pub_key_bio(BIO.MemoryBuffer(ks))

If ks contains unicode characters the operation will fail hence the recoding of ks.

Verifying a signature is a little tricky. The verify function is documented as accepting a data parameter. The parameter name is misleading. It is actually expecting data to contain a hash. The same hash used to generate the signature. Here is an example.

>>> from M2Crypto import RSA, BIO
>>> k = RSA.load_key('bank_cert.pem')
>>> data = "easy like sunday morning"
>>> from hashlib import sha1
>>> signature = k.sign(sha1(data).digest(), 'sha1')
>>> k.verify(sha1(data).digest(), signature, 'sha1')
1

0 comments: