certgen.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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="md5", **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 md5
  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, (issuerCert, issuerKey), serial, (notBefore, notAfter), digest="md5"):
  46. """
  47. Generate a certificate given a certificate request.
  48. Arguments: req - Certificate reqeust to use
  49. issuerCert - The certificate of the issuer
  50. issuerKey - The private key of the issuer
  51. serial - Serial number for the certificate
  52. notBefore - Timestamp (relative to now) when the certificate
  53. starts being valid
  54. notAfter - Timestamp (relative to now) when the certificate
  55. stops being valid
  56. digest - Digest method to use for signing, default is md5
  57. Returns: The signed certificate in an X509 object
  58. """
  59. cert = crypto.X509()
  60. cert.set_serial_number(serial)
  61. cert.gmtime_adj_notBefore(notBefore)
  62. cert.gmtime_adj_notAfter(notAfter)
  63. cert.set_issuer(issuerCert.get_subject())
  64. cert.set_subject(req.get_subject())
  65. cert.set_pubkey(req.get_pubkey())
  66. cert.sign(issuerKey, digest)
  67. return cert