create_self-signed.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. # This Source Code Form is subject to the terms of the Mozilla Public
  3. # License, v. 2.0. If a copy of the MPL was not distributed with this
  4. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. import sys
  6. import os
  7. import shutil
  8. import socket
  9. if len(sys.argv) < 2:
  10. sys.exit('Usage: %s directory to output certificates' % sys.argv[0])
  11. if not os.path.exists(sys.argv[1]):
  12. sys.exit('ERROR: Directory %s was not found!' % sys.argv[1])
  13. keysize = 2048
  14. if len(sys.argv) == 3:
  15. keysize = int(sys.argv[2])
  16. certsdir = os.path.dirname(os.path.abspath(__file__))
  17. os.environ['HOSTNAME'] = socket.gethostname()
  18. os.environ['OPENSSL_CONF'] = os.path.join(certsdir, "localhost.cnf")
  19. os.chdir(os.path.abspath(sys.argv[1]))
  20. os.system("""openssl genrsa -out ca.key {}""".format(keysize))
  21. os.system("""openssl req \
  22. -x509 \
  23. -new \
  24. -nodes \
  25. -key ca.key \
  26. -days 3650 \
  27. -subj "/C=DE/O=open62541/CN=open62541.org" \
  28. -out ca.crt""")
  29. os.system("""openssl req \
  30. -new \
  31. -newkey rsa:{} \
  32. -nodes \
  33. -subj "/C=DE/O=open62541/CN=open62541Server@localhost" \
  34. -keyout localhost.key \
  35. -out localhost.csr""".format(keysize))
  36. os.system("""openssl x509 -req \
  37. -days 3650 \
  38. -in localhost.csr \
  39. -CA ca.crt \
  40. -CAkey ca.key \
  41. -CAcreateserial \
  42. -out localhost.crt \
  43. -extfile $OPENSSL_CONF \
  44. -extensions v3_ca""")
  45. os.system("openssl x509 -in localhost.crt -outform der -out server_cert.der")
  46. os.system("openssl rsa -inform PEM -in localhost.key -outform DER -out server_key.der")
  47. os.remove("localhost.key")
  48. os.remove("localhost.crt")
  49. os.remove("localhost.csr")
  50. os.remove("ca.srl")
  51. # os.remove("ca.key")
  52. # os.remove("ca.crt")
  53. # if os.path.isfile(os.path.join(sys.argv[1], "server_cert.der")):
  54. # os.remove(os.path.join(sys.argv[1], "server_cert.der"))
  55. # shutil.move("server_cert.der", sys.argv[1])
  56. # if os.path.isfile(os.path.join(sys.argv[1], "ca.crt")):
  57. # os.remove(os.path.join(sys.argv[1], "ca.crt"))
  58. # shutil.move("ca.crt", sys.argv[1])
  59. print("Certificates generated in " + sys.argv[1])