certutil.py 1.76 KB
Newer Older
ale's avatar
ale committed
1 2 3
from OpenSSL import crypto
import socket

4 5 6 7 8 9
CSR_DIGEST = 'sha1'


def writeto(filename, contents):
    with open(filename, 'w') as fd:
        fd.write(contents)
ale's avatar
ale committed
10 11


12 13
def readfrom(filename):
    with open(filename, 'r') as fd:
ale's avatar
ale committed
14
        return fd.read()
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77


def create_rsa_key_pair(bits=1024):
    """Generate a new RSA key pair."""
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, bits)
    return pkey


def create_cert_request(pkey, **attrs):
    """Generate a new CSR using the given key."""
    if 'CN' not in attrs:
        attrs['CN'] = socket.gethostname()
    req = crypto.X509Req()
    subj = req.get_subject()
    for key, value in attrs.items():
        setattr(subj, key, value)
    req.set_pubkey(pkey)
    req.sign(pkey, CSR_DIGEST)
    return req


def sign_certificate(req, ca_key, ca_crt, serial_num, days,
                     extensions=None, digest='sha1'):
    cert = crypto.X509()
    cert.set_serial_number(serial_num)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(86400 * days)
    cert.set_issuer(ca_crt.get_subject())
    cert.set_subject(req.get_subject())
    cert.set_pubkey(req.get_pubkey())
    if extensions:
        cert.add_extensions(extensions)
    cert.sign(ca_key, digest)
    return cert


class FakeRevoked(object):

    def set_serial(self, serial):
        self.serial = serial


class FakeCRL(object):

    def __init__(self):
        self.entries = set()

    def get_revoked(self):
        return self.entries

    def add_revoked(self, r):
        self.entries.add(r)

    def export(self, cert, key, filetype, days):
        return ''


# Work around missing CRL implementation in PyOpenSSL < 0.11.
if not hasattr(crypto, 'CRL'):
    crypto.Revoked = FakeRevoked
    crypto.CRL = FakeCRL
    crypto.load_crl = lambda x, y: FakeCRL()