I'm using ssl.get_server_certificate function. It returns a pem string. For each server I try, I get the string, but it is missing a newline "\n" before the -----END CERTIFICATE----- text. Any subsequent use of the string makes openssl throw up with a "bad end line" error. ssl.PEM_cert_to_DER_cert can be used, and, subsequently the der string can be used elsewhere. Example: >>> fncert = ssl.get_server_certificate(("freenode.net", 443), 3) >>> fncert '-----BEGIN CERTIFICATE-----\nMIICFTCCAX6gAwIBAgIBAjANBgkqhkiG9w0BAQUFADBVMRswGQYDVQQKExJBcGFj\naGUgSFRUUCBTZXJ2ZXIxIjAgBgNVBAsTGUZvciB0ZXN0aW5nIHB1cnBvc2VzIG9u\nbHkxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wNzA1MDkxODM2MjVaFw0wODA1MDgx\nODM2MjVaMEwxGzAZBgNVBAoTEkFwYWNoZSBIVFRQIFNlcnZlcjEZMBcGA1UECxMQ\nVGVzdCBDZXJ0aWZpY2F0ZTESMBAGA1UEAxMJbG9jYWxob3N0MIGfMA0GCSqGSIb3\nDQEBAQUAA4GNADCBiQKBgQDYqJO6X9uwU0AyJ6H1WgYCZOqpZvdI96/LaDumT4Tl\nD6QvmXzAbM4okSHU3FEuSqR/tNv+eT5IZJKHVsXh0CiDduIYkLdqkLhEAbixjX/1\nfdCtGL4X0l42LqhK4TMFT5AxxsP1qFDXDvzl/yjxo9juVuZhCeqFr1YDKBffCIAn\ncwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAG0zi/KyzHxSsLHfrwTFh9330TaGj/3H\nuvhmBUPC3FOxbIH2y5CG/Ddg46756cfaxKKiqJV3I4dAgatQybE65ELc3wOWgs4v\n4VDGsFKbkmBLuCgnFaY+p4xvr2XL+bJmpm8+IQqW5Ob/OUSl7Vj4btHhF6VK29CI\n+DexDLRI0KqZ-----END CERTIFICATE-----\n' Notice no "\n" before -----END CERTIFICATE-----\n Platform: Linux x64 python 2.6.4
Did some more research and found this as the culprit: in Lib/ssl.py ############################# ... def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None): ... return DER_cert_to_PEM_cert(dercert) def DER_cert_to_PEM_cert(der_cert_bytes): """Takes a certificate in binary DER format and returns the PEM version of it as a string.""" if hasattr(base64, 'standard_b64encode'): # preferred because older API gets line-length wrong f = base64.standard_b64encode(der_cert_bytes) return (PEM_HEADER + '\n' + textwrap.fill(f, 64) + PEM_FOOTER + '\n') else: return (PEM_HEADER + '\n' + base64.encodestring(der_cert_bytes) + PEM_FOOTER + '\n') ############################ Notice no '\n' before the PEM_FOOTER
I think that's because encodestring tacks a 'courtesy newline' on to the end of the output it returns. textwrap.fill does't, and I'm guessing that's the code path that your installation is taking.