openmedialibrary/oml/node/cert.py

44 lines
1.6 KiB
Python
Raw Normal View History

2014-05-14 09:57:11 +00:00
# -*- coding: utf-8 -*-
import hashlib
2014-08-12 08:16:57 +00:00
import os
2014-05-14 09:57:11 +00:00
import OpenSSL
2014-08-12 08:16:57 +00:00
2014-05-14 09:57:11 +00:00
import settings
def get_fingerprint():
with open(settings.ssl_cert_path) as fd:
data = fd.read()
cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, data)
2014-09-05 23:44:17 +00:00
return hashlib.sha256(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, cert)).hexdigest()
2014-05-14 09:57:11 +00:00
def generate_ssl():
key = OpenSSL.crypto.PKey()
key.generate_key(OpenSSL.crypto.TYPE_RSA, 1024)
2014-05-14 09:57:11 +00:00
with open(settings.ssl_key_path, 'wb') as fd:
2014-09-02 22:32:44 +00:00
os.chmod(settings.ssl_key_path, 0o600)
2014-05-14 09:57:11 +00:00
fd.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key))
2014-09-02 22:32:44 +00:00
os.chmod(settings.ssl_key_path, 0o400)
2014-05-14 09:57:11 +00:00
ca = OpenSSL.crypto.X509()
ca.set_version(2)
ca.set_serial_number(1)
ca.get_subject().CN = settings.USER_ID
ca.gmtime_adj_notBefore(0)
ca.gmtime_adj_notAfter(24 * 60 * 60)
ca.set_issuer(ca.get_subject())
ca.set_pubkey(key)
ca.add_extensions([
2014-10-31 17:47:48 +00:00
OpenSSL.crypto.X509Extension(b"basicConstraints", True, b"CA:TRUE, pathlen:0"),
OpenSSL.crypto.X509Extension(b"nsCertType", True, b"sslCA"),
OpenSSL.crypto.X509Extension(b"extendedKeyUsage", True,
b"serverAuth,clientAuth,emailProtection,timeStamping,msCodeInd,msCodeCom,msCTLSign,msSGC,msEFS,nsSGC"),
OpenSSL.crypto.X509Extension(b"keyUsage", False, b"keyCertSign, cRLSign"),
OpenSSL.crypto.X509Extension(b"subjectKeyIdentifier", False, b"hash", subject=ca),
2014-05-14 09:57:11 +00:00
])
ca.sign(key, "sha1")
with open(settings.ssl_cert_path, 'wb') as fd:
fd.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, ca))
return get_fingerprint()