create_self-signed.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. print(certsdir)
  18. os.environ['HOSTNAME'] = socket.gethostname()
  19. openssl_conf = os.path.join(certsdir, "localhost.cnf")
  20. os.chdir(os.path.abspath(sys.argv[1]))
  21. os.system("""openssl genrsa -out ca.key {}""".format(keysize))
  22. os.system("""openssl req \
  23. -x509 \
  24. -new \
  25. -nodes \
  26. -key ca.key \
  27. -days 3650 \
  28. -subj "/C=DE/O=open62541/CN=open62541.org" \
  29. -out ca.crt""")
  30. os.system("""openssl req \
  31. -new \
  32. -newkey rsa:{} \
  33. -nodes \
  34. -subj "/C=DE/O=open62541/CN=open62541Server@localhost" \
  35. -keyout localhost.key \
  36. -out localhost.csr""".format(keysize))
  37. os.system("""openssl x509 -req \
  38. -days 3650 \
  39. -in localhost.csr \
  40. -CA ca.crt \
  41. -CAkey ca.key \
  42. -CAcreateserial \
  43. -out localhost.crt \
  44. -extfile {} \
  45. -extensions v3_ca""".format(openssl_conf))
  46. os.system("openssl x509 -in localhost.crt -outform der -out server_cert.der")
  47. os.system("openssl rsa -inform PEM -in localhost.key -outform DER -out server_key.der")
  48. os.remove("localhost.key")
  49. os.remove("localhost.crt")
  50. os.remove("localhost.csr")
  51. os.remove("ca.srl")
  52. # os.remove("ca.key")
  53. # os.remove("ca.crt")
  54. # if os.path.isfile(os.path.join(sys.argv[1], "server_cert.der")):
  55. # os.remove(os.path.join(sys.argv[1], "server_cert.der"))
  56. # shutil.move("server_cert.der", sys.argv[1])
  57. # if os.path.isfile(os.path.join(sys.argv[1], "ca.crt")):
  58. # os.remove(os.path.join(sys.argv[1], "ca.crt"))
  59. # shutil.move("ca.crt", sys.argv[1])
  60. print("Certificates generated in " + sys.argv[1])