secret.py
2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""DMS 密码加密保存:Windows DPAPI(本机级,LocalSystem 服务和管理员账号都能解开,拷到别的电脑解不开)。
config.ini 里写成 password = dpapi:AQAAANCMnd8BFdER...;明文密码也兼容(install.bat 会引导加密)。
非 Windows(Docker 演示环境)不支持 DPAPI,只能用明文。
"""
import base64
import ctypes
import os
PREFIX = "dpapi:"
CRYPTPROTECT_UI_FORBIDDEN = 0x1
CRYPTPROTECT_LOCAL_MACHINE = 0x4
class SecretError(Exception):
pass
if os.name == "nt":
from ctypes import wintypes
class _Blob(ctypes.Structure):
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
def _blob(data):
buf = ctypes.create_string_buffer(data, len(data))
return _Blob(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char))), buf
def _take(blob):
try:
return ctypes.string_at(blob.pbData, blob.cbData)
finally:
ctypes.windll.kernel32.LocalFree(blob.pbData)
def available():
return os.name == "nt"
def protect(text):
if not available():
raise SecretError("只有 Windows 支持 DPAPI 加密")
src, _keep = _blob(text.encode("utf-8"))
out = _Blob()
ok = ctypes.windll.crypt32.CryptProtectData(ctypes.byref(src), u"StoreEdge", None, None, None,
CRYPTPROTECT_UI_FORBIDDEN | CRYPTPROTECT_LOCAL_MACHINE, ctypes.byref(out))
if not ok:
raise SecretError("DPAPI 加密失败(错误码 %d)" % ctypes.GetLastError())
return PREFIX + base64.b64encode(_take(out)).decode("ascii")
def unprotect(value):
if not value or not value.startswith(PREFIX):
return value
if not available():
raise SecretError("config.ini 里的密码是 DPAPI 加密的,只能在加密它的那台 Windows 电脑上使用")
src, _keep = _blob(base64.b64decode(value[len(PREFIX):]))
out = _Blob()
ok = ctypes.windll.crypt32.CryptUnprotectData(ctypes.byref(src), None, None, None, None,
CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(out))
if not ok:
raise SecretError("DPAPI 解密失败(错误码 %d):密码可能是在另一台电脑上加密的,请重新运行 install.bat 设置密码"
% ctypes.GetLastError())
return _take(out).decode("utf-8")