Creating Certificates on Mac & Linux with Expect

Let’s see how we can create a certificate to test with AWS ELB. First manually and then in an automated way.

Step by Step Certificate Creation

Create private key. Enter a password you can remember, at least for a few minutes.

1
openssl genrsa -des3 -out server.key 2048

Create a certificate signing request. Enter your domain name for “Common Name” Don’t set a password when prompted.

1
openssl req -new -key server.key -out server.csr

Remove password.

1
2
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key

Sign your certificate.

1
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Now Let’s Automate with Expect

Create a file named keygen.sh

We will use expect in order to speed up certificate generation. Expect is a program that “talks” to other interactive programs according to a script.

You may just change domain variable and it should be fine.

Contents of keygen.sh

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/expect -f
set domain helloawsworld.com

spawn /usr/bin/openssl genrsa -des3 -out server.key 2048
expect "Enter pass phrase for server.key:"
send "hello\r"
expect "Verifying - Enter pass phrase for server.key:"
send "hello\r"
expect eof

spawn /usr/bin/openssl req -new -key server.key -out server.csr
expect "Enter pass phrase for server.key:"
send "hello\r"
expect "Country Name (2 letter code)*:"
send "\r"
expect "State or Province Name (full name)*:"
send "\r"
expect "Locality Name (eg, city)*:"
send "\r"
expect "Organization Name (eg, company)*:"
send "\r"
expect "Organizational Unit Name (eg, section)*:"
send "\r"
expect "Common Name (e.g. server FQDN or YOUR name)*:"
send "$domain\r"
expect "Email Address*:"
send "\r"
expect "A challenge password*:"
send "\r"
expect "An optional company name*:"
send "\r"
expect eof

spawn cp server.key server.key.org

spawn openssl rsa -in server.key.org -out server.key
expect "Enter pass phrase for server.key.org:"
send "hello\r"
expect eof

spawn rm server.key.org

spawn openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
expect eof

Make it executable and run it

1
2
3
4
$ chmod +x keygen.sh
$./keygen.sh
$ ls server*
server.csr      server.key      server.key.org      server.crt

As you see all files are created without any input so you can repeat the process many times or use to automate testing.

You will need server.key for private key and server.crt for public key certificate.

comments powered by Disqus