0
votes

Using Azure Key Vault Secret client library for Python I got the secret for the certificate which has an extracted private key.

-----BEGIN PRIVATE KEY

{private_key_value}

-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----

{certificate_value}

-----END CERTIFICATE-----

Is there package already made to get the two values (certificate and private key) separately for this scenario, or how can I extract them from the string? I need this to add a ssl_server_credenetials for my gRPC server, which takes - A list of pairs of the form [PEM-encoded private key, PEM-encoded certificate chain] Python gRPC

1

1 Answers

0
votes

If your certificate's content type is PEM and you get the .value of the secret with your certificate's name, you should get a PEM-encoded string like you describe. There's now a sample for azure-keyvault-certificates that shows how to get the private key from a certificate using pyOpenSSL, but if you want to parse the string you could do something like this:

from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient

credential = DefaultAzureCredential()
client = SecretClient("https://{vault-name}.vault.azure.net", credential)
secret = client.get_secret("cert-name")

def get_section_from_pem(pem_string, section):
    header = "-----BEGIN {}-----".format(section)
    footer = "-----END {}-----".format(section)
    header_start = pem_string.index(header)
    footer_start = pem_string.index(footer)
    content = pem_string[header_start + len(header) : footer_start]
    return content

private_key = get_section_from_pem(secret.value, "PRIVATE KEY")
certificate = get_section_from_pem(secret.value, "CERTIFICATE")

print("Private key: {}\nCertificate: {}".format(private_key, certificate))

(I work on the Azure SDK in Python)