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