Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top