0

I'm using the Python M2Crypto package to generate RSA keys.

>>> import M2Crypto
>>> rsa = M2Crypto.RSA.gen_key (2048, 65537)
.............................................................+++
............................+++
>>>

Notice that "openssl stuff". To suppress writing to stdout/err I usually do:

sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, 'w')

That has no effect in this case. I'm assuming this has to do with the way M2Crypto is wrapping OpenSSL.

Is there a way to stop it?

Cory
  • 3
  • 1

1 Answers1

3

I looked at the source /M2Crypto/RSA.py, found out what your issue was, and then realized I could have just read the docs. Always check the documentation first!!!

According to the docs for RSA.gen_key, gen_key has an optional argument called callback which allows you to specify a function to call whenever gen_key is called (ostensibly to provide feedback to the user). The default value for this call back prints stuff to stdout. Change your function call to:

>>> rsa = M2Crypto.RSA.gen_key (2048, 65537, callback=lambda x, y, z:None) 

And it should do the trick.

EDIT

Below is the relevant code from the M2PyCrypto source. Comments added by me.

def keygen_callback(p, n, out=sys.stdout): #sys.stdout is bound to `out` at definition time
    """
    Default callback for gen_key().
    """
    ch = ['.','+','*','\n']
    out.write(ch[p])
    out.flush()


def gen_key(bits, e, callback=keygen_callback): #keygen_callback is bound to `callback`
    #other code...
Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
  • Thanks! Is the out=sys.stdout assignment in the method definition done when the module is loaded in python and not when the method is called? I'm still unsure why setting sys.stdout to /dev/null didn't stop the output. – Cory Aug 02 '12 at 13:59
  • @Cory That's exactly what happens the value of that default parameter is set at the time of function definition. See [this answer](http://stackoverflow.com/a/11416002/1142167) to a (somewhat related) concept. – Joel Cornett Aug 02 '12 at 17:44