Avoid password prompt for keys and prompts for DN information


I am using following code to generate keys:

apt-get -qq -y install openssl;
mkdir -p /etc/apache2/ssl;
openssl genrsa -des3 -out server.key 1024;
openssl req -new -key server.key -out server.csr;
cp server.key server.key.org;
openssl rsa -in server.key.org -out server.key;
openssl x509 -req -days 12000 -in server.csr -signkey server.key -out server.crt;
mv server.crt  /etc/apache2/ssl/cert.pem;
mv server.key  /etc/apache2/ssl/cert.key;
rm -f server.key.orig;
rm -f server.csr

I have two questions:

  1. How can I skip the passphrase prompting? Would it be reasonably safe for me to do so? (as in it should not be downright foolish like anyone should be able to hack the certificate)

  2. How do I avoid the prompting for the country name, organization etc. I hope I can give them on command prompt (the man page shows only top level options for OpenSSL)


Answers:


Edit: This is by far my most popular answer, and it's been a few years on now so I've added an ECDSA variant. If you can use ECDSA you should.


You can supply all of that information on the command line.

One step self-signed password-less certificate generation:

RSA Version

openssl req \
    -new \
    -newkey rsa:4096 \
    -days 365 \
    -nodes \
    -x509 \
    -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" \
    -keyout www.example.com.key \
    -out www.example.com.cert

ECDSA version

openssl req \
    -new \
    -newkey ec \
    -pkeyopt ec_paramgen_curve:prime256v1 \
    -days 365 \
    -nodes \
    -x509 \
    -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" \
    -keyout www.example.com.key \
    -out www.example.com.cert

All of the openssl subcommands have their own man page. See man req.


Specifically addressing your questions and to be more explicit about exactly which options are in effect:

  1. The -nodes flag signals to not encrypt the key, thus you do not need a password. You could also use the -passout arg flag. See PASS PHRASE ARGUMENTS in the openssl(1) man page for how to format the arg.

  2. Using the -subj flag you can specify the subject (example is above).