Skip to content

Instantly share code, notes, and snippets.

@catleeball
Last active May 26, 2019 07:51
Show Gist options
  • Save catleeball/d69cd73ca545f8cb8f183dad33de9118 to your computer and use it in GitHub Desktop.
Save catleeball/d69cd73ca545f8cb8f183dad33de9118 to your computer and use it in GitHub Desktop.
def _MaybeTextFile(filename):
"""Check if text file based on file(1)
Implementation stolen shamelessly from:
https://stackoverflow.com/a/7392391/2873090
Args:
filename: String describing a path to a file
Returns:
Boolean: True if the first 1024 bytes seem to indicate a text file
"""
textchars = bytearray({7, 8, 9, 10, 12, 13, 27} |
set(range(0x20, 0x100)) - {0x7f})
return lambda bytes: bool(bytes.translate(None, textchars))
def _MaybeP12File(filename):
"""Check if file has expected ending .p12 or .pfx and isn't text file
Args:
filename: String describing a path to a file
Returns:
Boolean: True if file has expected ending and isn't text file
"""
return not _MaybeTextFile(filename) and any(
filename.lower().endswith('.p12'),
filename.lower().endswith('.pfx'),
)
def _ProbablyP12File(filename):
"""Checks first hextet of file to see if it matches .p12 file header
Anecdotally, .p12 files appear to always start with hextet 0x3082. Check
the first hextet to see if it matches this pattern.
This isn't explicitly verified in the PKCS 12 spec, but testing several valid
PKCS 12 files, this appears to be the case.
TODO: Consult with SMEs to verify this assumption is correct. If so, remove
the _MaybeP12File() function and rename this function.
Args:
filename: String describing a path to a file
Returns:
Boolean: True if file starts with 0x3082
"""
p12_header = b'3082'
with open(filename, 'rb') as f:
hextet = binascii.hexlify(bytearray(f.read(2)))
return p12_header == hextet
def _GetPrivateKey(filename):
if _ProbablyP12File(filename) or _MaybeP12File(filename):
with open(filename, 'rb') as private_key_file:
return (True, private_key_file.read())
else:
with io.open(filename, 'r', encoding=UTF8) as private_key_file:
return (False, private_key_file.read())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment