Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions Lib/ssl.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@
"""

import ipaddress
import textwrap
import re
import sys
import os
Expand Down Expand Up @@ -1201,9 +1200,10 @@ def DER_cert_to_PEM_cert(der_cert_bytes):
PEM version of it as a string."""

f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
return (PEM_HEADER + '\n' +
textwrap.fill(f, 64) + '\n' +
PEM_FOOTER + '\n')
ss = [PEM_HEADER]
ss += [f[i:i+64] for i in range(0, len(f), 64)]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 for the idea

Please don't use += and use a self-explaining local variable name:

lines = [PEM_HEADER]
lines.extend(f[i:i+64] for i in range(0, len(f), 64))
lines.extend([PEM_FOOTER, ''])
return '\n'.join(lines)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My first impulse was to add a similar comment. But actually this doesn't matter. All lists here are small I hope, so copying lists doesn't add much overhead. On other hand, the variant with extend() and generator expression add their own overheads.

  1. Generator expression is slightly slower than a list comprehension.
  2. list.extend() is special cased for tuples and list. It is slower with general iterators.
  3. Calling a method is slower than executing an operator.
  4. I didn't checked, but maybe PEM_FOOTER + '\n' is faster than [PEM_FOOTER, ''].

Hence the current code looks good enough to me. It is enough fast and looks enough Pythonic. If there are opportunities to enhance it, it is not worth the spent time.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm sorry about variable name. I didn't care about name for very short scope variables.

In case of performance, as serhiy said, cert size won't be arbitrary large.
And old code used temporal string for body part. This commit didn't make anythong worse.

$ ./python -m perf timeit -s "import textwrap; s='a'*1000" -- 'textwrap.fill(s, 60)'
.....................
Mean +- std dev: 192 us +- 10 us

$ ./python -m perf timeit -s "import textwrap; s='a'*1000" -- 'x=[]; x+=[s[i:i+60] for i in range(0,len(s),60)]; "\n".join(x)'
.....................
Mean +- std dev: 4.66 us +- 0.06 us

ss.append(PEM_FOOTER + '\n')
return '\n'.join(ss)

def PEM_cert_to_DER_cert(pem_cert_string):
"""Takes a certificate in ASCII PEM format and returns the
Expand Down