Given a Windows DPAPI file with values stored as Secure Strings How would one decrypt those values in Python? The secure string is created with PowerShell like this.
$global:Credentials.AuthToken = Read-Host -AsSecureString -Prompt "Auth-Token:"
and these values are stored using DPAPI on a Windows 10 or similar Computer.
Using Python extract the Secure String from the DPAPI file and feed it to the function below. The secure string will be stored as a base64 encoded value.
Note: when you read the DPAPI file created by PowerShell ensure you use "utf-16-le" encoding.
import codecs
import win32crypt
import base64
def decrypt(b64string):
b64decodedstring = base64.b64decode(b64string)
clear = win32crypt.CryptUnprotectData(b64decodedstring, None, None, None, 0)
return clear[1].decode("utf-16-le")
For a secure string in Windows the value is stored on disk as a base64 encoded hex. So extract the clear text value like this running it through the function twice with an encode of the hex value back to base64 in between.
decrypt(codecs.encode(codecs.decode(decrypt(ValueExtractedFromDPAPIGoesHere), 'hex'), 'base64').decode())
Note: you will need to run Python as the user whose DPAPI you are trying to access the secure strings from.