I have a python script that retrieves a RSA private key from Azure Key Vault. Trying to serialize the key value gives:
ValueError: Could not deserialize key data.
key_bytes looks like "b'\\xb8w\\xb7\\xce{s\\xf7\\xa0\\xce\\xba\\xf5#\\x07\\x8b?\\x1d\\xc9m..."
Code:
from azure.keyvault import KeyVaultClient, KeyVaultAuthentication
from azure.common.credentials import ServicePrincipalCredentials
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import dsa
from cryptography.hazmat.primitives import serialization
subscription_id = "xxx"
VAULT_URL = "xxx"
KEY_ID = "xxx"
KEY_VERSION = "xxx"
credentials = ServicePrincipalCredentials(
client_id = 'xxx',
secret = 'xxx',
tenant = 'xxx'
)
client = KeyVaultClient(credentials)
key_bundle = client.get_key(VAULT_URL,
KEY_ID,
KEY_VERSION)
key_bytes = key_bundle.key.n
p_key = serialization.load_pem_private_key(
key_bytes,
password='xxx',
backend=default_backend()
)
By loading the key from Blob storage in .p8 format the above key serialization works. Key vault requires the key to be saved in pem format.
I have tried different decodings etc but I haven't had success in decoding the bytes. Any help or tips to solve this would be appreciated.
Note I was working with jwcrypto.
Not sure if this is relevant, but I've been struggling with JWKs the last few days. One thing that helped me was base64 encoding and decoding e and n (exponent and modulus of the key): base64.urlsafe_b64encode(n).decode()
What that does is it takes the ASCII-encoded (I believe) bytes n-value (b'...') and returns base64-encoded bytes then decoded into a string as that's what was required for my input.
b'\\xd4b\\xd3/"Vi\\x8b\\xce\\xaf...\\xf1\\xec\\xcd
b'1GLTLyJWaYvOrwdje1O3...OvHszQ==
'1GLTLyJWaYvOrwdje1O3...OvHszQ==
(note the '==' at the end, which is what you'd expect to see at the end of a private key)Again, not sure if that helps.
This gives some context of parameters and from what I understand of this article, you can't actually get a private key out of a Key Vault, just a public one.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.