How to Generate a Private Key and CSR from Command Line

By | 2013/01/11

Use the following command to generate a private key and certificate signing request (CSR):

$ openssl req -new -newkey rsa:2048 -nodes -keyout server_private.key -out server_csr.csr


In the dialog that follows, pay particular attention to the CommonName (CN) indication. If you need a certificate for example.com, use example.com (exactly) as the CN.

For example, if you need a certificate for mail.example.com, use mail.example.com as the CN.

$ openssl req -new -newkey rsa:2048 -nodes -keyout server_private.key -out server_csr.csr
Generating a 2048 bit RSA private key
....................................................................+++
.......+++
writing new private key to 'server_private.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:NC
Locality Name (eg, city) []:Raleigh
Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Company      
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:example.com
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:


You are then left with two files, the private key and CSR.

$ ls
server_csr.csr  server_private.key

The .csr file can then be submitted to a certificate authority like rapidssl, etc.

$ cat server_csr.csr 
-----BEGIN CERTIFICATE REQUEST-----
MIICnDCCAYQCAQAwVzELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAk5DMRAwDgYDVQQH
DAdSYWxlaWdoMRMwEQYDVQQKDApNeSBDb21wYW55MRQwEgYDVQQDDAtleGFtcGxl
LmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALC0nppN0HRMNEEu
Vv423bS3S7Qb1SIzQ7YPmvOz4LdVWlzVNQZlt3daqcfIF18NhZWOOLzpcJ0rvfcx
RPkMobMLk9zwymrCfijMIHQnW4hRYjOpmfYFBxUM71Tm6HSFL1TLKaNzTuXoYS6V
yCLMqfVjXR6dpz167ZqrR/0xa8yeABrdouUZhwTNr46zj6nUxZtDagK/GNoq1VA/
713HKDQGBcHiOlA3ZBSchW/kKQi4pseCrOGoV2U6uA/CeSFNx100PUInXhKH3zyQ
aX/q9yT1iTVTQG1lc2uTfovSADLMGq5e+7kxjfBY9VObZpJw5RGXSNjQLu2oze2r
le0cQIsCAwEAAaAAMA0GCSqGSIb3DQEBBQUAA4IBAQA8c2t6vRpfcBkhL5UxYo6v
QfIz6VPaEjmEChJ9za1POMWz1T/NdBvj2zYkG/8xBzcYrByltjuNMBABUhKAW0b8
/D3+Xjfet5/gLiHXLaBwr7FM75IodFZzUs41TOKiITQS8LaSiXNcCBwLNF6OCffQ
Ic4jGNM/lw/zfFRfoOGByrWb2O1sjTAdZB/TkOI6FDV6rsRJwlanDwj0zkp0dgQ1
wDzAzwpPLV5PdzNRqvHTGMJHohq6513pY+Qt+lyU5ay64JHFc6+mJeQrxTbYR0xu
0BFKLV9LonbAMzfUR5r397+qe9fyitjJBCy9HgYO/murvksOM8OyXzInAD+6hmVd
-----END CERTIFICATE REQUEST-----

Cool!