create_self-signed.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. os.chdir(os.path.dirname(os.path.abspath(__file__)))
  14. os.environ['HOSTNAME'] = socket.gethostname()
  15. os.environ['OPENSSL_CONF'] = os.path.join(os.getcwd(), "localhost.cnf")
  16. os.system("""openssl genrsa -out ca.key 2048""")
  17. os.system("""openssl req \
  18. -x509 \
  19. -new \
  20. -nodes \
  21. -key ca.key \
  22. -days 3650 \
  23. -subj "/C=DE/O=open62541/CN=open62541.org" \
  24. -out ca.crt""")
  25. os.system("""openssl req \
  26. -new \
  27. -newkey rsa:2048 \
  28. -nodes \
  29. -subj "/C=DE/O=open62541/CN=open62541Server@localhost" \
  30. -config localhost.cnf \
  31. -keyout localhost.key \
  32. -out localhost.csr""")
  33. os.system("""openssl x509 -req \
  34. -days 3650 \
  35. -in localhost.csr \
  36. -CA ca.crt \
  37. -CAkey ca.key \
  38. -CAcreateserial \
  39. -out localhost.crt \
  40. -extensions v3_ca \
  41. -extfile localhost.cnf""")
  42. os.system("""openssl x509 -in localhost.crt -outform der -out server_cert.der""")
  43. #we will need these files later
  44. os.remove("localhost.key") #we will need it later
  45. os.remove("localhost.crt")
  46. os.remove("localhost.csr")
  47. os.remove("ca.key")
  48. os.remove("ca.srl")
  49. if os.path.isfile(os.path.join(sys.argv[1], "server_cert.der")):
  50. os.remove(os.path.join(sys.argv[1], "server_cert.der"))
  51. shutil.move("server_cert.der", sys.argv[1])
  52. if os.path.isfile(os.path.join(sys.argv[1], "ca.crt")):
  53. os.remove(os.path.join(sys.argv[1], "ca.crt"))
  54. shutil.move("ca.crt", sys.argv[1])
  55. print("Certificates generated in " + sys.argv[1])