genca.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. from OpenSSL import crypto, SSL
  2. def cert_gen(
  3. emailAddress="emailAddress",
  4. commonName="commonName",
  5. countryName="NT",
  6. localityName="localityName",
  7. stateOrProvinceName="stateOrProvinceName",
  8. organizationName="organizationName",
  9. organizationUnitName="organizationUnitName",
  10. serialNumber=0,
  11. validityStartInSeconds=0,
  12. validityEndInSeconds=10*365*24*60*60,
  13. KEY_FILE = "private.key",
  14. CERT_FILE="selfsigned.crt"):
  15. #can look at generated file using openssl:
  16. #openssl x509 -inform pem -in selfsigned.crt -noout -text
  17. # create a key pair
  18. k = crypto.PKey()
  19. k.generate_key(crypto.TYPE_RSA, 4096)
  20. # create a self-signed cert
  21. cert = crypto.X509()
  22. cert.get_subject().C = countryName
  23. cert.get_subject().ST = stateOrProvinceName
  24. cert.get_subject().L = localityName
  25. cert.get_subject().O = organizationName
  26. cert.get_subject().OU = organizationUnitName
  27. cert.get_subject().CN = commonName
  28. cert.get_subject().emailAddress = emailAddress
  29. cert.set_serial_number(serialNumber)
  30. cert.gmtime_adj_notBefore(0)
  31. cert.gmtime_adj_notAfter(validityEndInSeconds)
  32. cert.set_issuer(cert.get_subject())
  33. cert.set_pubkey(k)
  34. cert.sign(k, 'sha512')
  35. with open(CERT_FILE, "wt") as f:
  36. f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf-8"))
  37. with open(KEY_FILE, "wt") as f:
  38. f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode("utf-8"))
  39. cert_gen()