create_self-signed.py 1.8 KB

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