certgen.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # -*- coding: latin-1 -*-
  2. #
  3. # Copyright (C) AB Strakt
  4. # Copyright (C) Jean-Paul Calderone
  5. # See LICENSE for details.
  6. """
  7. Certificate generation module.
  8. """
  9. from OpenSSL import crypto
  10. TYPE_RSA = crypto.TYPE_RSA
  11. TYPE_DSA = crypto.TYPE_DSA
  12. def createKeyPair(type, bits):
  13. """
  14. Create a public/private key pair.
  15. Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA
  16. bits - Number of bits to use in the key
  17. Returns: The public/private key pair in a PKey object
  18. """
  19. pkey = crypto.PKey()
  20. pkey.generate_key(type, bits)
  21. return pkey
  22. def createCertRequest(pkey, digest="sha256", **name):
  23. """
  24. Create a certificate request.
  25. Arguments: pkey - The key to associate with the request
  26. digest - Digestion method to use for signing, default is sha256
  27. **name - The name of the subject of the request, possible
  28. arguments are:
  29. C - Country name
  30. ST - State or province name
  31. L - Locality name
  32. O - Organization name
  33. OU - Organizational unit name
  34. CN - Common name
  35. emailAddress - E-mail address
  36. Returns: The certificate request in an X509Req object
  37. """
  38. req = crypto.X509Req()
  39. subj = req.get_subject()
  40. for key, value in name.items():
  41. setattr(subj, key, value)
  42. req.set_pubkey(pkey)
  43. req.sign(pkey, digest)
  44. return req
  45. def createCertificate(req, issuerCertKey, serial, validityPeriod,
  46. digest="sha256"):
  47. """
  48. Generate a certificate given a certificate request.
  49. Arguments: req - Certificate request to use
  50. issuerCert - The certificate of the issuer
  51. issuerKey - The private key of the issuer
  52. serial - Serial number for the certificate
  53. notBefore - Timestamp (relative to now) when the certificate
  54. starts being valid
  55. notAfter - Timestamp (relative to now) when the certificate
  56. stops being valid
  57. digest - Digest method to use for signing, default is sha256
  58. Returns: The signed certificate in an X509 object
  59. """
  60. issuerCert, issuerKey = issuerCertKey
  61. notBefore, notAfter = validityPeriod
  62. cert = crypto.X509()
  63. cert.set_serial_number(serial)
  64. cert.gmtime_adj_notBefore(notBefore)
  65. cert.gmtime_adj_notAfter(notAfter)
  66. cert.set_issuer(issuerCert.get_subject())
  67. cert.set_subject(req.get_subject())
  68. cert.set_pubkey(req.get_pubkey())
  69. cert.sign(issuerKey, digest)
  70. return cert