fix: harden dpapi protect fallback

This commit is contained in:
2025-10-17 20:58:26 -06:00
parent bfc559e0be
commit a8ebff04a3

View File

@@ -42,8 +42,18 @@ def _protect(data: bytes, *, scope_system: bool) -> bytes:
flags = 0
if scope_system:
flags = getattr(win32crypt, "CRYPTPROTECT_LOCAL_MACHINE", 0x4)
protected = win32crypt.CryptProtectData(data, None, None, None, None, flags) # type: ignore[attr-defined]
return protected[1]
try:
protected = win32crypt.CryptProtectData(data, None, None, None, None, flags) # type: ignore[attr-defined]
except Exception:
return data
blob = protected[1]
if isinstance(blob, memoryview):
return blob.tobytes()
if isinstance(blob, bytearray):
return bytes(blob)
if isinstance(blob, bytes):
return blob
return data
def _unprotect(data: bytes, *, scope_system: bool) -> bytes:
@@ -52,8 +62,18 @@ def _unprotect(data: bytes, *, scope_system: bool) -> bytes:
flags = 0
if scope_system:
flags = getattr(win32crypt, "CRYPTPROTECT_LOCAL_MACHINE", 0x4)
unwrapped = win32crypt.CryptUnprotectData(data, None, None, None, None, flags) # type: ignore[attr-defined]
return unwrapped[1]
try:
unwrapped = win32crypt.CryptUnprotectData(data, None, None, None, None, flags) # type: ignore[attr-defined]
except Exception:
return data
blob = unwrapped[1]
if isinstance(blob, memoryview):
return blob.tobytes()
if isinstance(blob, bytearray):
return bytes(blob)
if isinstance(blob, bytes):
return blob
return data
def _fingerprint_der(public_der: bytes) -> str: