Generating an RSA key pair
This entry kicks off a series of snippets on using M2Crypto.
In this entry we'll look at generating an RSA key pair using M2Crypto.
>>> from M2Crypto import RSA
>>> import pydoc
>>> pydoc.help('M2Crypto.RSA.gen_key')
Help on function gen_key in M2Crypto.RSA:
M2Crypto.RSA.gen_key = gen_key(bits, e, callback=util.passphrase_callback)
Factory function that generates an RSA key pair and instantiates
an RSA object from it.
_bits_ is the key length in bits.
_e_ is the value for e, the RSA public exponent.
(Optional) _callback_ is a Python callback object that will be
invoked during key generation; its usual purpose is to provide visual
feedback.
>>> key = RSA.gen_key(1024, 65537)
....++++++
............++++++
>>> key
<M2Crypto.RSA.RSA instance at 0x85c26ec>
>>>
To save the key pair, use the method save_key. This method uses a callback to provide a passphrase. The default callback uses Python's getpass module. Here we'll use a GUI callback.
First we define the GUI callback code:
from Tkinter import *
class PPCB:
def __init__(self):
self.box = Tk()
Label(self.box, text='Passphrase:').grid(row=0, sticky=W)
self.e1 = Entry(self.box, show='*')
self.e1.grid(row=0, column=1)
Button(self.box, text='Ok', command=self.doit).grid(row=1, column=1)
def doit(self):
self.pp = self.e1.get()
self.box.destroy()
def __call__(self, *args):
self.box.mainloop()
return self.pp
Do it:
>>> key.save_key('/tmp/key.pem', 'aes_128_cbc', PPCB())
The GUI pops up:
Type a passphrase and click 'Ok'.
1
>>> print open('/tmp/key.pem').read()
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,80AF6A3162C4804418E76A351B358091
j+5KYWU8FUmFeBVm1xhydojjihrP+wc+F37G/z5OzINddlLrazoKqw55bxX3HDhR
C8pbkm5oaR9L8Q4nVNJmoswPP6MN0jtrs/h+cJYVY47Ov8Ko/u4XlHBCXae1IqiR
3lbMSPi4qOh96CitwYUUzTCPPGCIZHVcDprsXsqXHGLmn15lc+svX35P+kpbVYVv
jsKoM2OgKVnGzC6m6ujTs1ccHESEXAjBbZm50okdAoo9t5pcbtFSuzK601cPaTSt
fbfF676OptP5lhjVHmwpQxIzy8SHD8ol1cIDaEsp6uXU1gYKY7tlNL1BW5Raud4s
zrrVIVgQrCbtyTl9k0hM/XMMtRETPpgI7uLCV4NlnPRY6ErFxPxZGkZkfneCYZ4w
ProAec9DRHYZjA4dJeXHpVKorqbJApcU6ToYN1EWGkVy8LGRwh3n4ngpPUSsSlhw
4/9D69/PAa2XgDxoz1JqZxnCRjFzpaORBGYx2crAB+kVQT90mlYoByw9QqPKOrzl
YZhdaadAeCok68qmM4uTao413J6MvOz+npSPDhBn7uc2yzf0yzYlWVJJ6+cUcnj5
XQrHuFNczMaHrq3L/97tLyK2hOFSXPdmqaT8rwX2jDHtsq5eDEnL2yzQIAJ9C8pJ
bJvVm8TOAszKeXpLfRjBxTSzDvtNuS1+dr7UdJSXkqKrVDPjVV+1d977WPOdwZOS
wPl35Z2jPIU6OENGjQbGjxTRpn7xAIA3IzEjDh4rugaoWSBDxE4aLY226AlVC2Ud
RQF+6iynqlbHAnG6txKJuc6fROKOEWABasDC4m7R80oi/7GPi/Rw1ygtWh63CJ0X
-----END RSA PRIVATE KEY-----
>>>
Modifying the callback to prompt for the passphrase twice and confirm that the supplied passphrases are the same is left as an exercise for the reader. ;-)