Import a pem format public key using import_key API

Sharma, Arpana 51 Reputation points
2022-11-24T21:35:35.423+00:00

Is there a way to import a .pem format public key into the Azure key vault in python?

Ideally, import_key() method takes the JsonWebKey format to import a RSA public key.

Is there a way to convert a .pem format public key into JsonWebKey object to be passed into import_key SDK call.

Our use case is that we need to import an externally generated RSA public key into the Azure key vault.

Azure Key Vault
Azure Key Vault
An Azure service that is used to manage and protect cryptographic keys and other secrets used by cloud apps and services.
1,184 questions
{count} votes

Accepted answer
  1. Fabian Gonzalez 501 Reputation points Microsoft Employee
    2022-12-06T15:42:46.297+00:00

    @Sharma, Arpana Azure Key Vault only supports asymmetric keys (key pair), you can't import a public key into Key Vault as a key, it will return an error saying that the file does not contain a private key. If you want to import a public-only key, you should do it as a secret.

    2 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Shweta Mathur 29,531 Reputation points Microsoft Employee
    2022-11-28T06:04:55.587+00:00

    Hi @Sharma, Arpana ,

    Thanks for reaching out and apologies for delay in response.

    I understand you are trying to convert .pem format public key to JsonWebKey(JWK) to pass in import_key() in python.

    First, you need to load the PEM into a public key object(pubKey)

    from cryptography import x509
    from cryptography.hazmat.backends import default_backend
    from cryptography.x509.oid import NameOID
    pem_cert=open("/../../../fd.pem","rb").read()
    cert = x509.load_pem_x509_certificate(pem_cert, default_backend())
    pubKey = cert.public_key()
    print(pubKey)

    and then this can be converted using

    jwk = pubKey.getJwk() which will return the JWK in the most compact JSON format possible.

    Also, there is a sample reference to import PEM certificate into Azure Key Vault in the python:

    https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/keyvault/azure-keyvault-certificates/samples/import_certificate.py

    Hope this will help.

    Thanks,
    Shweta

    -------------------------------------

    Please remember to "Accept Answer" if answer helped you.

    0 comments No comments