mirror of
https://github.com/ansible-collections/community.crypto.git
synced 2026-05-06 13:22:58 +00:00
Improve PEM identification. (#628)
This commit is contained in:
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user