create_self-signed.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import sys
  2. import os
  3. import shutil
  4. import socket
  5. if len(sys.argv) < 2:
  6. sys.exit('Usage: %s directory to output certificates' % sys.argv[0])
  7. if not os.path.exists(sys.argv[1]):
  8. sys.exit('ERROR: Directory %s was not found!' % sys.argv[1])
  9. os.chdir(os.path.dirname(os.path.abspath(__file__)))
  10. os.environ['HOSTNAME'] = socket.gethostname()
  11. os.environ['OPENSSL_CONF'] = os.path.join(os.getcwd(), "localhost.cnf")
  12. os.system("""openssl genrsa -out ca.key 2048""")
  13. os.system("""openssl req \
  14. -x509 \
  15. -new \
  16. -nodes \
  17. -key ca.key \
  18. -days 3650 \
  19. -subj "/C=DE/O=open62541/CN=open62541.org" \
  20. -out ca.crt""")
  21. os.system("""openssl req \
  22. -new \
  23. -newkey rsa:2048 \
  24. -nodes \
  25. -subj "/C=DE/O=open62541/CN=open62541Server@localhost" \
  26. -config localhost.cnf \
  27. -keyout localhost.key \
  28. -out localhost.csr""")
  29. os.system("""openssl x509 -req \
  30. -days 3650 \
  31. -in localhost.csr \
  32. -CA ca.crt \
  33. -CAkey ca.key \
  34. -CAcreateserial \
  35. -out localhost.crt \
  36. -extensions v3_ca \
  37. -extfile localhost.cnf""")
  38. os.system("""openssl x509 -in localhost.crt -outform der -out server_cert.der""")
  39. #we will need these files later
  40. os.remove("localhost.key") #we will need it later
  41. os.remove("localhost.crt")
  42. os.remove("localhost.csr")
  43. os.remove("ca.key")
  44. os.remove("ca.srl")
  45. if os.path.isfile(os.path.join(sys.argv[1], "server_cert.der")):
  46. os.remove(os.path.join(sys.argv[1], "server_cert.der"))
  47. shutil.move("server_cert.der", sys.argv[1])
  48. if os.path.isfile(os.path.join(sys.argv[1], "ca.crt")):
  49. os.remove(os.path.join(sys.argv[1], "ca.crt"))
  50. shutil.move("ca.crt", sys.argv[1])