<s> from OpenSSL . SSL import FILETYPE_PEM <EOL> from twisted . internet . ssl import Certificate , KeyPair , CertificateOptions <EOL> from collections import namedtuple <EOL> PEMObjects = namedtuple ( '<STR_LIT>' , [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> def objectsFromPEM ( pemdata ) : <EOL> """<STR_LIT>""" <EOL> certificates = [ ] <EOL> keys = [ ] <EOL> for line in pemdata . split ( "<STR_LIT:\n>" ) : <EOL> if line . startswith ( '<STR_LIT>' ) : <EOL> if '<STR_LIT>' in line : <EOL> blobs = certificates <EOL> else : <EOL> blobs = keys <EOL> blobs . append ( '<STR_LIT>' ) <EOL> blobs [ - <NUM_LIT:1> ] += line <EOL> blobs [ - <NUM_LIT:1> ] += '<STR_LIT:\n>' <EOL> keys = [ KeyPair . load ( key , FILETYPE_PEM ) for key in keys ] <EOL> certificates = [ Certificate . loadPEM ( certificate ) <EOL> for certificate in certificates ] <EOL> return PEMObjects ( keys = keys , certificates = certificates ) <EOL> def certificateOptionsFromPileOfPEM ( pemdata ) : <EOL> objects = objectsFromPEM ( pemdata ) <EOL> if len ( objects . keys ) != <NUM_LIT:1> : <EOL> raise ValueError ( "<STR_LIT>" <EOL> % tuple ( [ len ( objects . keys ) ] ) ) <EOL> privateKey = objects . keys [ <NUM_LIT:0> ] <EOL> certificatesByFingerprint = dict ( <EOL> [ ( certificate . getPublicKey ( ) . keyHash ( ) , certificate ) <EOL> for certificate in objects . certificates ] <EOL> ) <EOL> if privateKey . keyHash ( ) not in certificatesByFingerprint : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> openSSLCert = certificatesByFingerprint . pop ( privateKey . keyHash ( ) ) . original <EOL> openSSLKey = privateKey . original <EOL> openSSLChain = [ c . original for c in certificatesByFingerprint . values ( ) ] <EOL> return CertificateOptions ( certificate = openSSLCert , privateKey = openSSLKey , <EOL> extraCertChain = openSSLChain ) </s>
