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