Files
myrzx_bot/ranch_assistant/credentials.py
T

59 lines
2.4 KiB
Python

"""Remember desktop credentials using the current Windows user's DPAPI key."""
import base64
import ctypes
from ctypes import wintypes
import json
import os
from pathlib import Path
class Blob(ctypes.Structure):
_fields_ = [("size", wintypes.DWORD), ("data", ctypes.POINTER(ctypes.c_ubyte))]
def crypt(data, decrypt=False):
if os.name != "nt":
raise OSError("此密码保存方式需要 Windows")
crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
function = crypt32.CryptUnprotectData if decrypt else crypt32.CryptProtectData
function.argtypes = [ctypes.POINTER(Blob), ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(Blob)]
function.restype = wintypes.BOOL
kernel32.LocalFree.argtypes = [ctypes.c_void_p]
kernel32.LocalFree.restype = ctypes.c_void_p
buffer = ctypes.create_string_buffer(data)
source = Blob(len(data), ctypes.cast(buffer, ctypes.POINTER(ctypes.c_ubyte)))
output = Blob()
if not function(ctypes.byref(source), None, None, None, None, 1, ctypes.byref(output)):
raise OSError("Windows 无法读取或保存此登录密码")
try:
return ctypes.string_at(output.data, output.size)
finally:
kernel32.LocalFree(ctypes.cast(output.data, ctypes.c_void_p))
class CredentialStore:
def __init__(self, folder):
self.path = Path(folder) / "credentials.json"
def save(self, account, password, remember=True):
value = {"remember": bool(remember), "scheme": "windows-dpapi"}
if remember:
value.update(account=account, password=base64.b64encode(crypt(password.encode("utf-8"))).decode("ascii"))
self.path.parent.mkdir(parents=True, exist_ok=True)
temporary = self.path.with_suffix(".tmp")
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding="utf-8")
temporary.replace(self.path)
def load(self):
if not self.path.exists():
return True, "", ""
value = json.loads(self.path.read_text(encoding="utf-8"))
if not value.get("remember"):
return False, "", ""
if value.get("scheme") != "windows-dpapi":
raise ValueError("无法识别保存的密码格式")
password = crypt(base64.b64decode(value["password"], validate=True), decrypt=True).decode("utf-8")
return True, value["account"], password