certgen.py 2.6 KB

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