4 # Copyright (C) Martin Sjogren and AB Strakt 2001, All rights reserved
6 # $Id: certgen.py,v 1.2 2004/07/22 12:01:25 martin Exp $
9 Certificate generation and validation module.
12 from OpenSSL import crypto
13 import time, calendar, datetime
15 TYPE_RSA = crypto.TYPE_RSA
16 TYPE_DSA = crypto.TYPE_DSA
18 def createKeyPair(type, bits):
20 Create a public/private key pair.
22 Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA
23 bits - Number of bits to use in the key
24 Returns: The public/private key pair in a PKey object
27 pkey.generate_key(type, bits)
30 def createCertRequest(pkey, name, digest="md5"):
32 Create a certificate request.
34 Arguments: pkey - The key to associate with the request
35 digest - Digestion method to use for signing, default is md5
36 **name - The name of the subject of the request, possible
39 ST - State or province name
42 OU - Organizational unit name
44 emailAddress - E-mail address
45 Returns: The certificate request in an X509Req object
47 req = crypto.X509Req()
48 subj = req.get_subject()
49 for (key,value) in name.items():
50 setattr(subj, key, value)
52 req.sign(pkey, digest)
55 def createCertificate(req, (issuerCert, issuerKey), serial, (notBefore, notAfter), extensions=[], digest="md5"):
57 Generate a certificate given a certificate request.
59 Arguments: req - Certificate reqeust to use
60 issuerCert - The certificate of the issuer
61 issuerKey - The private key of the issuer
62 serial - Serial number for the certificate
63 notBefore - Timestamp (relative to now) when the certificate
65 notAfter - Timestamp (relative to now) when the certificate
67 digest - Digest method to use for signing, default is md5
68 Returns: The signed certificate in an X509 object
71 cert.set_serial_number(serial)
72 cert.gmtime_adj_notBefore(notBefore)
73 cert.gmtime_adj_notAfter(notAfter)
74 cert.set_issuer(issuerCert.get_subject())
75 cert.set_subject(req.get_subject())
76 cert.set_pubkey(req.get_pubkey())
79 for name, critical, value in extensions:
80 ext = crypto.X509Extension (name, critical, value)
82 cert.add_extensions(extList)
83 cert.sign(issuerKey, digest)
87 #checks if a certificate is valid in terms of validity periods
88 def check_valid(usercert):
90 Method that ensures the issuer cert has
91 valid, not_before and not_after fields
94 before_time = usercert.get_not_before()
95 after_time = usercert.get_not_after()
96 before_tuple = time.strptime(str(before_time), "%b %d %H:%M:%S %Y %Z")
97 after_tuple = time.strptime(str(after_time), "%b %d %H:%M:%S %Y %Z")
98 starts = datetime.timedelta(seconds=calendar.timegm(before_tuple))
99 expires = datetime.timedelta(seconds=calendar.timegm(after_tuple))
100 now = datetime.timedelta(seconds=time.time())
101 time_delta = expires - now
104 if time_delta.days < 0:
106 #cert is not yet valid
107 time_delta = now - starts
108 if time_delta.days < 0: