views:

75

answers:

2

Hi, I'm writing a script to generate a CSR in Python. The script is very simple. I generate an RSA private key by using the following:

keycmd = "openssl genrsa -out mykey.pem 2048"
keyprocess = Popen(keycmd, shell=True, stdout=PIPE)

csrcmd = "openssl req -new -key mykey.pem -subj "+ subj + " -out mycsr.csr"
reqprocess = Popen(csrcmd, shell=True, stdout=PIPE)

However, I want to add the functionality to encrypt the private key with a password is the user desires. This is normally done by including the option "-des3" in the genrsa command, but I don't know how to pipe a string from Python standard input to the OpenSSL process. Any help would be appreciated.

What I want to do is:

keycmd = "openssl genrsa -des3 -out mykey.pem 2048"
keyprocess = Popen(keycmd, shell=True, stdin=PIPE, stdout=PIPE)
keyprocess.communicate("password")
keyprocess.communicate("password")

It's not working however, the script just freezes and never gets past the first communicate statement.

+1  A: 

Have you tried the Pexpect module ?

import pexpect

child = pexpect.spawn(keycmd)
child.expect("Enter pass phrase")
child.sendline("password")

child.expect("Verifying - Enter pass phrase")
child.sendline("password")
Andre Holzner
+1  A: 

Add the option -passout stdin to the openssl genrsa command, and it will read the passphrase from standard input. That should allow you to send it in via communicate.

There are several other values you can provide to the -passout option to obtain the passphrase from another source. See the OpenSSL man page for details.

David Zaslavsky
I'm entering the following into the shell:openssl genrsa -out mykey.pem -passout stdin 1024It waits for input from stdin. I type in a word and press Enter. However, the private key generated is not encrypted. Any ideas why this is?
Sean Nilan
I'm guessing it's because you didn't provide the `-des3` option. `-passout` only tells OpenSSL to read a password from the given source, it doesn't tell it to use the password for anything.
David Zaslavsky