generate-certificates.sh 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/bin/sh
  2. # Generate a CA with a self-signed root certificate that then signs the server certificate
  3. # Based on the OpenSSL Cookbook by Ivan Ristic:
  4. # https://www.feistyduck.com/library/openssl-cookbook/online/
  5. #
  6. # Especially, see chapter 1.5. Creating a private Certification Authority:
  7. # https://www.feistyduck.com/library/openssl-cookbook/online/openssl-command-line/private-ca.html
  8. export KEY_PATH=keys
  9. export CRT_PATH=certificates
  10. export CA_PATH=ca
  11. # Create environment.
  12. # $CA_PATH is deleted in the end.
  13. # If new certificates need to be issued, this needs to be done before the cleanup in the end.
  14. mkdir -p $KEY_PATH $CRT_PATH $CA_PATH/db $CA_PATH/private $CA_PATH/certificates
  15. touch $CA_PATH/db/index
  16. openssl rand -hex 16 > $CA_PATH/db/serial
  17. # Generate all private keys
  18. openssl genpkey -algorithm ed25519 -out $KEY_PATH/root-ca.key
  19. openssl genpkey -algorithm ed25519 -out $KEY_PATH/server.key
  20. openssl genpkey -algorithm ed25519 -out $KEY_PATH/client.key
  21. # For the server, we also need the public key
  22. openssl pkey -in $KEY_PATH/server.key -pubout -out $KEY_PATH/server.pub
  23. # Generate a Certificate Signing Request for the Root CA based on a config file
  24. openssl req -new \
  25. -config root-ca.cnf -out root-ca.csr \
  26. -key $KEY_PATH/root-ca.key
  27. # Self-sign the root certificate
  28. openssl ca -batch \
  29. -selfsign -config root-ca.cnf \
  30. -extensions ca_ext \
  31. -in root-ca.csr -out $CRT_PATH/root-ca.crt -notext
  32. # Create a Certificate Signing request for the server certificate
  33. openssl req -new \
  34. -config server.cnf -out server.csr \
  35. -key $KEY_PATH/server.key
  36. openssl req -text -in server.csr -noout
  37. # Issue the server certificate
  38. openssl ca -batch \
  39. -config root-ca.cnf \
  40. -extensions server_ext \
  41. -extfile server.cnf -extensions ext \
  42. -in server.csr -out $CRT_PATH/server.crt -notext \
  43. -days 1825
  44. # Create a Certificate Signing request for the client certificate
  45. openssl req -new \
  46. -config client.cnf -out client.csr \
  47. -key $KEY_PATH/client.key
  48. # Issue the client certificate
  49. openssl ca -batch \
  50. -config root-ca.cnf \
  51. -extensions client_ext \
  52. -in client.csr -out $CRT_PATH/client.crt -notext \
  53. -days 1825
  54. # Clean up
  55. # IMPORTANT: If new certificates should be issued, $CA_PATH and its files MUST NOT be deleted!
  56. # New certificates can be created in this script before cleaning up.
  57. rm -rf *.csr $CA_PATH