Skip to content

Commit 709fea1

Browse files
committed
Cleaner implementation and precise docs on SHA256
1 parent bbeb494 commit 709fea1

File tree

2 files changed

+43
-32
lines changed

2 files changed

+43
-32
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,6 @@ msal_cache.bin
6262

6363
.env
6464
.perf.baseline
65+
66+
*.pfx
67+
.vscode/settings.json

msal/application.py

Lines changed: 40 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -66,16 +66,21 @@ def _str2bytes(raw):
6666
except:
6767
return raw
6868

69-
def _extract_cert_and_thumbprints(private_key, cert):
69+
def _extract_cert_and_thumbprints(cert):
7070
# Cert concepts https://security.stackexchange.com/a/226758/125264
7171
from cryptography.hazmat.primitives import hashes, serialization
72-
cert_pem = cert.public_bytes(encoding=serialization.Encoding.PEM).decode()
72+
cert_pem = cert.public_bytes( # Requires cryptography 1.0+
73+
encoding=serialization.Encoding.PEM).decode()
7374
x5c = [
74-
'\n'.join(cert_pem.splitlines()[1:-1])
75+
'\n'.join(
76+
cert_pem.splitlines()
77+
[1:-1] # Strip the "--- header ---" and "--- footer ---"
78+
)
7579
]
76-
sha256_thumbprint = cert.fingerprint(hashes.SHA256()).hex()
77-
sha1_thumbprint = cert.fingerprint(hashes.SHA1()).hex()
78-
return private_key, sha256_thumbprint, sha1_thumbprint, x5c
80+
# https://cryptography.io/en/latest/x509/reference/#x-509-certificate-object
81+
sha256_thumbprint = cert.fingerprint(hashes.SHA256()).hex() # Requires cryptography 0.7+
82+
sha1_thumbprint = cert.fingerprint(hashes.SHA1()).hex() # Requires cryptography 0.7+
83+
return sha256_thumbprint, sha1_thumbprint, x5c
7984

8085
def _parse_pfx(pfx_path, passphrase_bytes):
8186
# Cert concepts https://security.stackexchange.com/a/226758/125264
@@ -86,7 +91,8 @@ def _parse_pfx(pfx_path, passphrase_bytes):
8691
f.read(), passphrase_bytes)
8792
if not (private_key and cert):
8893
raise ValueError("Your PFX file shall contain both private key and cert")
89-
return _extract_cert_and_thumbprints(private_key, cert)
94+
sha256_thumbprint, sha1_thumbprint, x5c = _extract_cert_and_thumbprints(cert)
95+
return private_key, sha256_thumbprint, sha1_thumbprint, x5c
9096

9197

9298
def _load_private_key_from_pem_str(private_key_pem_str, passphrase_bytes):
@@ -290,7 +296,10 @@ def __init__(
290296
291297
{
292298
"private_key": "...-----BEGIN PRIVATE KEY-----... in PEM format",
293-
"thumbprint": "An SHA-1 thumbprint such as A1B2C3D4E5F6...", # Optional since version 1.35.0
299+
"thumbprint": "An SHA-1 thumbprint such as A1B2C3D4E5F6..."
300+
"Changed in version 1.35.0, if thumbprint is absent"
301+
"and a public_certificate is present, MSAL will"
302+
"automatically calculate an SHA-256 thumbprint instead.",
294303
"passphrase": "Needed if the private_key is encrypted (Added in version 1.6.0)",
295304
"public_certificate": "...-----BEGIN CERTIFICATE-----...", # Needed if you use Subject Name/Issuer auth. Added in version 0.5.0.
296305
}
@@ -805,31 +814,30 @@ def _build_client(self, client_credential, authority, skip_regional_client=False
805814
passphrase_bytes)
806815
if client_credential.get("public_certificate") is True and x5c:
807816
headers["x5c"] = x5c
808-
elif (client_credential.get("private_key")
809-
and client_credential.get("public_certificate")
810-
and not client_credential.get("thumbprint")): #in case user does not pass thumbprint but only certificate and private key
811-
if passphrase_bytes: # PEM with passphrase
812-
private_key = _load_private_key_from_pem_str(
813-
client_credential['private_key'], passphrase_bytes)
814-
else: # PEM without passphrase
815-
private_key = client_credential['private_key']
816-
817-
private_key, sha256_thumbprint, sha1_thumbprint, x5c =(
818-
_extract_cert_and_thumbprints(
819-
private_key,
820-
client_credential['public_certificate']))
821-
if x5c:
822-
headers["x5c"] = x5c
823-
824-
elif (
825-
client_credential.get("private_key") # PEM blob
826-
and client_credential.get("thumbprint")):
827-
sha1_thumbprint = client_credential["thumbprint"]
828-
if passphrase_bytes:
829-
private_key = _load_private_key_from_pem_str(
817+
elif client_credential.get("private_key"): # PEM blob
818+
private_key = ( # handles both encrypted and unencrypted
819+
_load_private_key_from_pem_str(
830820
client_credential['private_key'], passphrase_bytes)
831-
else: # PEM without passphrase
832-
private_key = client_credential['private_key']
821+
if passphrase_bytes
822+
else client_credential['private_key']
823+
)
824+
825+
# Determine thumbprints based on what's provided
826+
if client_credential.get("thumbprint"):
827+
# User provided a thumbprint - use it as SHA-1 (legacy/manual approach)
828+
sha1_thumbprint = client_credential["thumbprint"]
829+
sha256_thumbprint = None
830+
elif isinstance(client_credential.get('public_certificate'), str):
831+
# No thumbprint provided, but we have a certificate to calculate thumbprints
832+
from cryptography import x509
833+
cert = x509.load_pem_x509_certificate(
834+
_str2bytes(client_credential['public_certificate']))
835+
sha256_thumbprint, sha1_thumbprint, headers["x5c"] = (
836+
_extract_cert_and_thumbprints(cert))
837+
else:
838+
raise ValueError(
839+
"You must provide either 'thumbprint' or 'public_certificate' "
840+
"from which the thumbprint can be calculated.")
833841
else:
834842
raise ValueError(
835843
"client_credential needs to follow this format "

0 commit comments

Comments
 (0)