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