4
if sys.platform != 'win32':
5
raise ImportError('Windows-only module')
8
from ctypes import Structure, wintypes, POINTER, windll, \
9
WinDLL, c_void_p, WINFUNCTYPE, cast, create_string_buffer, \
10
c_char_p, byref, memmove
13
# Crypto API ctypes bindings
15
class DATA_BLOB(Structure):
16
_fields_ = [('cbData', wintypes.DWORD),
17
('pbData', POINTER(wintypes.BYTE))]
19
class CRYPTPROTECT_PROMPTSTRUCT(Structure):
20
_fields_ = [('cbSize', wintypes.DWORD),
21
('dwPromptFlags', wintypes.DWORD),
22
('hwndApp', wintypes.HWND),
23
('szPrompt', POINTER(wintypes.WCHAR))]
25
# Flags for CRYPTPROTECT_PROMPTSTRUCT
27
CRYPTPROTECT_PROMPT_ON_UNPROTECT = 1
28
CRYPTPROTECT_PROMPT_ON_PROTECT = 2
30
# Flags for CryptProtectData/CryptUnprotectData
32
CRYPTPROTECT_UI_FORBIDDEN = 0x01
33
CRYPTPROTECT_LOCAL_MACHINE = 0x04
34
CRYPTPROTECT_CRED_SYNC = 0x08
35
CRYPTPROTECT_AUDIT = 0x10
36
CRYPTPROTECT_NO_RECOVERY = 0x20
37
CRYPTPROTECT_VERIFY_PROTECTION = 0x40
38
CRYPTPROTECT_CRED_REGENERATE = 0x80
40
# Crypto API Functions
42
_dll = WinDLL('CRYPT32.DLL')
44
CryptProtectData = WINFUNCTYPE(wintypes.BOOL,
46
POINTER(wintypes.WCHAR),
49
POINTER(CRYPTPROTECT_PROMPTSTRUCT),
51
POINTER(DATA_BLOB))(('CryptProtectData', _dll))
53
CryptUnprotectData = WINFUNCTYPE(wintypes.BOOL,
55
POINTER(wintypes.WCHAR),
58
POINTER(CRYPTPROTECT_PROMPTSTRUCT),
60
POINTER(DATA_BLOB))(('CryptUnprotectData', _dll))
64
def encrypt(data, non_interactive=0):
65
blobin = DATA_BLOB(cbData=len(data),
66
pbData=cast(c_char_p(data),
67
POINTER(wintypes.BYTE)))
70
if not CryptProtectData(byref(blobin),
71
u'python-keyring-lib.win32crypto',
73
CRYPTPROTECT_UI_FORBIDDEN,
75
raise OSError("Can't encrypt")
77
encrypted = create_string_buffer(blobout.cbData)
78
memmove(encrypted, blobout.pbData, blobout.cbData)
79
windll.kernel32.LocalFree(blobout.pbData)
82
def decrypt(encrypted, non_interactive=0):
83
blobin = DATA_BLOB(cbData=len(encrypted),
84
pbData=cast(c_char_p(encrypted),
85
POINTER(wintypes.BYTE)))
88
if not CryptUnprotectData(byref(blobin),
89
u'python-keyring-lib.win32crypto',
91
CRYPTPROTECT_UI_FORBIDDEN,
93
raise OSError("Can't decrypt")
95
data = create_string_buffer(blobout.cbData)
96
memmove(data, blobout.pbData, blobout.cbData)
97
windll.kernel32.LocalFree(blobout.pbData)