Improve PEM identification. (#628)

This commit is contained in:
Felix Fontein
2023-06-27 17:35:55 +02:00
committed by GitHub
parent ed6285e083
commit 83af72a3bc
3 changed files with 79 additions and 4 deletions

View File

@@ -14,10 +14,13 @@ PKCS8_PRIVATEKEY_NAMES = ('PRIVATE KEY', 'ENCRYPTED PRIVATE KEY')
PKCS1_PRIVATEKEY_SUFFIX = ' PRIVATE KEY'
def identify_pem_format(content):
def identify_pem_format(content, encoding='utf-8'):
'''Given the contents of a binary file, tests whether this could be a PEM file.'''
try:
lines = content.decode('utf-8').splitlines(False)
first_pem = extract_first_pem(content.decode(encoding))
if first_pem is None:
return False
lines = first_pem.splitlines(False)
if lines[0].startswith(PEM_START) and lines[0].endswith(PEM_END) and len(lines[0]) > len(PEM_START) + len(PEM_END):
return True
except UnicodeDecodeError:
@@ -25,14 +28,17 @@ def identify_pem_format(content):
return False
def identify_private_key_format(content):
def identify_private_key_format(content, encoding='utf-8'):
'''Given the contents of a private key file, identifies its format.'''
# See https://github.com/openssl/openssl/blob/master/crypto/pem/pem_pkey.c#L40-L85
# (PEM_read_bio_PrivateKey)
# and https://github.com/openssl/openssl/blob/master/include/openssl/pem.h#L46-L47
# (PEM_STRING_PKCS8, PEM_STRING_PKCS8INF)
try:
lines = content.decode('utf-8').splitlines(False)
first_pem = extract_first_pem(content.decode(encoding))
if first_pem is None:
return 'raw'
lines = first_pem.splitlines(False)
if lines[0].startswith(PEM_START) and lines[0].endswith(PEM_END) and len(lines[0]) > len(PEM_START) + len(PEM_END):
name = lines[0][len(PEM_START):-len(PEM_END)]
if name in PKCS8_PRIVATEKEY_NAMES: