-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
only_noticed_pypi_pem_after_i_wrote_this.py
53 lines (41 loc) · 1.7 KB
/
only_noticed_pypi_pem_after_i_wrote_this.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
from OpenSSL.SSL import FILETYPE_PEM
from twisted.internet.ssl import Certificate, KeyPair, CertificateOptions
from collections import namedtuple
PEMObjects = namedtuple('PEMObjects', ['certificates', 'keys'])
def objectsFromPEM(pemdata):
"""
Load some objects from a PEM.
"""
certificates = []
keys = []
blobs = [b""]
for line in pemdata.split(b"\n"):
if line.startswith(b'-----BEGIN'):
if b'CERTIFICATE' in line:
blobs = certificates
else:
blobs = keys
blobs.append(b'')
blobs[-1] += line
blobs[-1] += b'\n'
keys = [KeyPair.load(key, FILETYPE_PEM) for key in keys]
certificates = [Certificate.loadPEM(certificate)
for certificate in certificates]
return PEMObjects(keys=keys, certificates=certificates)
def certificateOptionsFromPileOfPEM(pemdata):
objects = objectsFromPEM(pemdata)
if len(objects.keys) != 1:
raise ValueError("Expected 1 private key, found %d"
% tuple([len(objects.keys)]))
privateKey = objects.keys[0]
certificatesByFingerprint = dict(
[(certificate.getPublicKey().keyHash(), certificate)
for certificate in objects.certificates]
)
if privateKey.keyHash() not in certificatesByFingerprint:
raise ValueError("No certificate matching %s found")
openSSLCert = certificatesByFingerprint.pop(privateKey.keyHash()).original
openSSLKey = privateKey.original
openSSLChain = [c.original for c in certificatesByFingerprint.values()]
return CertificateOptions(certificate=openSSLCert, privateKey=openSSLKey,
extraCertChain=openSSLChain)