1
|
|
|
import base64 |
2
|
|
|
|
3
|
|
|
from azure.identity import AzureCliCredential |
4
|
|
|
from azure.keyvault.secrets import SecretClient |
5
|
|
|
from cryptography.hazmat.backends import default_backend |
6
|
|
|
from cryptography.hazmat.primitives import hashes |
7
|
|
|
from cryptography.hazmat.primitives._serialization import Encoding, PrivateFormat, NoEncryption |
8
|
|
|
from cryptography.hazmat.primitives.serialization import pkcs12 |
9
|
|
|
|
10
|
|
|
|
11
|
|
|
def get_certificate(vault_url, certificate_name): |
12
|
|
|
credential = AzureCliCredential( |
13
|
|
|
tenant_id="72f988bf-86f1-41af-91ab-2d7cd011db47" |
14
|
|
|
) |
15
|
|
|
secret_client = SecretClient(vault_url=vault_url, credential=credential) |
16
|
|
|
return secret_client.get_secret(certificate_name) |
17
|
|
|
|
18
|
|
|
|
19
|
|
|
def get_client_credential(vault_url, certificate_name): |
20
|
|
|
cert_key = get_certificate(vault_url, certificate_name) |
21
|
|
|
|
22
|
|
|
# https://github.com/Azure/azure-sdk-for-python/blob/07d10639d7e47f4852eaeb74aef5d569db499d6e/sdk/identity/azure-identity/azure/identity/_credentials/certificate.py#L101-L123 |
23
|
|
|
private_key, cert, _ = pkcs12.load_key_and_certificates( |
24
|
|
|
base64.b64decode(cert_key.value), None, backend=default_backend() |
25
|
|
|
) |
26
|
|
|
|
27
|
|
|
return { |
28
|
|
|
"private_key": private_key.private_bytes( |
29
|
|
|
encoding=Encoding.PEM, |
30
|
|
|
format=PrivateFormat.PKCS8, |
31
|
|
|
encryption_algorithm=NoEncryption()).decode(), |
32
|
|
|
"thumbprint": cert.fingerprint(hashes.SHA1()).hex(), |
33
|
|
|
"public_certificate": cert.public_bytes(Encoding.PEM).decode(), |
34
|
|
|
} |
35
|
|
|
|