1#!/bin/bash
2
3#
4# Generates:
5#  - user-cert-chain.crt
6#  - user-cert-chain.key
7#
8
9set -e
10
11WORKDIR='temp'
12
13mkdir "$WORKDIR"
14cp ca.conf "$WORKDIR/"
15pushd "$WORKDIR"
16
17## Generate root CA
18mkdir -p rootca/{certs,crl,newcerts,private}
19pushd rootca
20touch index.txt
21echo '1000' > serial
22openssl req \
23    -config ../ca.conf \
24    -new \
25    -x509 \
26    -days 7300 \
27    -sha256 \
28    -extensions v3_ca \
29    -keyout private/ca.key.pem \
30    -out certs/ca.cert.pem
31popd
32
33## Generate Intermediate CA
34mkdir intermediate intermediate/{certs,crl,csr,newcerts,private}
35touch intermediate/index.txt
36
37echo '1000' > intermediate/serial
38echo '1000' > intermediate/crlnumber
39
40openssl req \
41    -config ca.conf \
42    -new \
43    -sha256 \
44    -keyout intermediate/private/intermediate.key.pem \
45    -out intermediate/csr/intermediate.csr.pem
46
47openssl ca \
48    -config ca.conf \
49    -name RootCA \
50    -extensions v3_intermediate_ca \
51    -days 3650 \
52    -notext \
53    -md sha256 \
54    -in intermediate/csr/intermediate.csr.pem \
55    -out intermediate/certs/intermediate.cert.pem
56
57## Generate client cert
58openssl req \
59    -config ca.conf \
60    -newkey rsa:1024 \
61    -keyout user.key.pem \
62    -nodes \
63    -days 3650 \
64    -out user.csr.pem
65
66openssl ca \
67    -config ca.conf \
68    -name IntermediateCA \
69    -extensions usr_cert \
70    -days 365 \
71    -notext \
72    -md sha256 \
73    -in user.csr.pem \
74    -out user.cert.pem
75
76popd # WORKDIR
77
78## Convert client cert to acceptable form
79cat \
80    "$WORKDIR"/user.cert.pem \
81    "$WORKDIR"/intermediate/certs/intermediate.cert.pem \
82    "$WORKDIR"/rootca/certs/ca.cert.pem \
83    > user-cert-chain.crt
84
85openssl pkcs8 \
86    -topk8 \
87    -nocrypt \
88    -inform PEM \
89    -outform DER \
90    -in "$WORKDIR"/user.key.pem \
91    -out user-cert-chain.key
92
93rm -r "$WORKDIR"