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 = Nonedef 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 cdef 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 Truedef 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 pairs = "a"*2000 # test dataedata = rsa.encrypt (s)sign = rsa.sign (s)ddata = rsa.decrypt (edata)assert rsa.verify (ddata, sign) == True`