def parse_issuer_cred(issuer_cred):
"""
Given an X509 PEM file in the form of a string, parses it into sections
by the PEM delimiters of: -----BEGIN <label>----- and -----END <label>----
Confirms the sections can be decoded in the proxy credential order of:
issuer cert, issuer private key, proxy chain of 0 or more certs .
Returns the issuer cert and private key as loaded cryptography objects
and the proxy chain as a potentially empty string.
"""
# get each section of the PEM file
sections = re.findall(
"-----BEGIN.*?-----.*?-----END.*?-----", issuer_cred, flags=re.DOTALL)
try:
issuer_cert = sections[0]
issuer_private_key = sections[1]
issuer_chain_certs = sections[2:]
except IndexError:
raise ValueError("Unable to parse PEM data in credentials, "
"make sure the X.509 file is in PEM format and "
"consists of the issuer cert, issuer private key, "
"and proxy chain (if any) in that order.")
# then validate that each section of data can be decoded as expected
try:
loaded_cert = x509.load_pem_x509_certificate(
six.b(issuer_cert), default_backend())
loaded_private_key = serialization.load_pem_private_key(
six.b(issuer_private_key),
password=None, backend=default_backend())
for chain_cert in issuer_chain_certs:
x509.load_pem_x509_certificate(
six.b(chain_cert), default_backend())
issuer_chain = "".join(issuer_chain_certs)
except ValueError:
raise ValueError("Failed to decode PEM data in credentials. Make sure "
"the X.509 file consists of the issuer cert, "
"issuer private key, and proxy chain (if any) "
"in that order.")
# return loaded cryptography objects and the issuer chain
return loaded_cert, loaded_private_key, issuer_chain
评论列表
文章目录