Initial import to Tizen
[profile/ivi/python-pyOpenSSL.git] / examples / certgen.py
1 # -*- coding: latin-1 -*-
2 #
3 # Copyright (C) AB Strakt
4 # Copyright (C) Jean-Paul Calderone
5 # See LICENSE for details.
6
7 """
8 Certificate generation module.
9 """
10
11 from OpenSSL import crypto
12
13 TYPE_RSA = crypto.TYPE_RSA
14 TYPE_DSA = crypto.TYPE_DSA
15
16 def createKeyPair(type, bits):
17     """
18     Create a public/private key pair.
19
20     Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA
21                bits - Number of bits to use in the key
22     Returns:   The public/private key pair in a PKey object
23     """
24     pkey = crypto.PKey()
25     pkey.generate_key(type, bits)
26     return pkey
27
28 def createCertRequest(pkey, digest="md5", **name):
29     """
30     Create a certificate request.
31
32     Arguments: pkey   - The key to associate with the request
33                digest - Digestion method to use for signing, default is md5
34                **name - The name of the subject of the request, possible
35                         arguments are:
36                           C     - Country name
37                           ST    - State or province name
38                           L     - Locality name
39                           O     - Organization name
40                           OU    - Organizational unit name
41                           CN    - Common name
42                           emailAddress - E-mail address
43     Returns:   The certificate request in an X509Req object
44     """
45     req = crypto.X509Req()
46     subj = req.get_subject()
47
48     for (key,value) in name.items():
49         setattr(subj, key, value)
50
51     req.set_pubkey(pkey)
52     req.sign(pkey, digest)
53     return req
54
55 def createCertificate(req, (issuerCert, issuerKey), serial, (notBefore, notAfter), digest="md5"):
56     """
57     Generate a certificate given a certificate request.
58
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
64                             starts being valid
65                notAfter   - Timestamp (relative to now) when the certificate
66                             stops being valid
67                digest     - Digest method to use for signing, default is md5
68     Returns:   The signed certificate in an X509 object
69     """
70     cert = crypto.X509()
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())
77     cert.sign(issuerKey, digest)
78     return cert
79