1#!/bin/bash
2set -eu
3
4target_dir="${1:-.}"
5days=3650
6rsa_bits=2048
7org="httplib2-test"
8server_cn="localhost"
9subj_prefix="/C=ZZ/ST=./L=./O=$org/OU=."
10
11main() {
12	cd "$target_dir"
13	gen
14	check
15}
16
17check() {
18	echo "- check keys" >&2
19	openssl rsa -in ca.key -check -noout
20	openssl rsa -in client.key -check -noout
21	openssl rsa -in client_encrypted.key -check -noout -passin pass:12345
22	openssl rsa -in server.key -check -noout
23
24	echo "- check certs" >&2
25	for f in *.pem ; do
26		openssl x509 -in "$f" -checkend 3600 -noout
27	done
28}
29
30gen() {
31	echo "- generate keys, if absent" >&2
32	[[ -f ca.key ]] || openssl genrsa -out ca.key $rsa_bits
33	[[ -f client.key ]] || openssl genrsa -out client.key $rsa_bits
34	[[ -f client_encrypted.key ]] || openssl rsa -in client.key -out client_encrypted.key -aes128 -passout pass:12345
35	[[ -f server.key ]] || openssl genrsa -out server.key $rsa_bits
36
37	echo "- generate CA" >&2
38	openssl req -batch -new -nodes -x509 -days $days -subj "$subj_prefix/CN=$org-CA" -key ca.key -out ca.pem
39	openssl req -batch -new -nodes -x509 -days $days -subj "$subj_prefix/CN=$org-CA-unused" -key ca.key -out ca_unused.pem
40
41	echo "- generate client cert" >&2
42	openssl req -batch -new -nodes -out tmp.csr -key client.key -subj "$subj_prefix/CN=$org-client"
43	openssl x509 -req -in tmp.csr -CA ca.pem -CAkey ca.key -CAcreateserial -out client.crt -days $days -serial -fingerprint
44	cat client.crt client.key >client.pem
45	cat client.crt ca.pem client.key >client_chain.pem
46
47	echo "- generate encrypted client cert" >&2
48	openssl req -batch -new -nodes -out tmp.csr -key client_encrypted.key -passin pass:12345 -subj "$subj_prefix/CN=$org-client-enc"
49	openssl x509 -req -in tmp.csr -CA ca.pem -CAkey ca.key -CAcreateserial -out client_encrypted.crt -days $days -serial -fingerprint
50	cat client_encrypted.crt client_encrypted.key >client_encrypted.pem
51
52	echo "- generate server cert" >&2
53	openssl req -batch -new -nodes -out tmp.csr -key server.key -subj "$subj_prefix/CN=$server_cn"
54	openssl x509 -req -in tmp.csr -CA ca.pem -CAkey ca.key -CAcreateserial -out server.crt -days $days -serial -fingerprint
55	cat server.crt server.key >server.pem
56	cat server.crt ca.pem server.key >server_chain.pem
57
58	rm tmp.csr
59}
60
61main
62