Saturday, November 14, 2009

Python and RSA


There are many Python toolkits for crypto, so I hope I've done the best choice (at least for now). This is a simple utility class for managing RSA keys, a sort of wrappera to the m2crypto class.

import M2Crypto
class RSA (object):
def __init__ (self, bits=1024, padding=M2Crypto.RSA.pkcs1_padding, exp=65537):
self.bits = bits
self.padding = padding
self.exp = exp
self.rsa = None

def generate (self):
self.rsa = M2Crypto.RSA.gen_key(
self.bits, self.exp, lambda x: None)

def encrypt (self, s):
c = ""
bytes = self.bits/8-11
for i in range(0, len(s), bytes):
c += self.rsa.public_encrypt (s[i:i+bytes], self.padding)
return c

def sign (self, s, algo="sha1"):
dgst = M2Crypto.EVP.MessageDigest (algo)
dgst.update (s)
return self.rsa.sign (dgst.digest (), algo)

def verify (self, s, sign, algo="sha1"):
dgst = M2Crypto.EVP.MessageDigest (algo)
dgst.update (s)
try:
self.rsa.verify (dgst.digest (), sign, algo)
except:
return False
return True

def decrypt (self, c):
s = ""
bytes = self.bits/8
for i in range(0, len(c), bytes):
s += self.rsa.private_decrypt (c[i:i+bytes], self.padding)
return s
Example usage:

rsa = RSA ()
rsa.generate () # generate key pair
s = "a"*2000 # test data
edata = rsa.encrypt (s)
sign = rsa.sign (s)

ddata = rsa.decrypt (edata)
assert rsa.verify (ddata, sign) == True

1 comment:

rolobio said...

This really helped me out. Thanks a lot.