The python 密钥环库 https://pypi.python.org/pypi/keyring与集成CryptProtectData https://msdn.microsoft.com/en-us/library/windows/desktop/aa380261(v=vs.85).aspxWindows 上的 API(以及 Mac 和 Linux 上的相关 API),使用用户的登录凭据加密数据。
简单用法:
import keyring
# the service is just a namespace for your app
service_id = 'IM_YOUR_APP!'
keyring.set_password(service_id, 'dustin', 'my secret password')
password = keyring.get_password(service_id, 'dustin') # retrieve password
如果要将用户名存储在密钥环上,请使用:
import keyring
MAGIC_USERNAME_KEY = 'im_the_magic_username_key'
# the service is just a namespace for your app
service_id = 'IM_YOUR_APP!'
username = 'dustin'
# save password
keyring.set_password(service_id, username, "password")
# optionally, abuse `set_password` to save username onto keyring
# we're just using some known magic string in the username field
keyring.set_password(service_id, MAGIC_USERNAME_KEY, username)
稍后从钥匙圈获取您的信息
# again, abusing `get_password` to get the username.
# after all, the keyring is just a key-value store
username = keyring.get_password(service_id, MAGIC_USERNAME_KEY)
password = keyring.get_password(service_id, username)
项目使用用户的操作系统凭据进行加密,因此在您的用户帐户中运行的其他应用程序将能够访问密码。
为了掩盖该漏洞,您可以在将密码存储在密钥环上之前以某种方式加密/混淆密码。当然,任何针对您的脚本的人都只能查看源代码并找出如何解密/取消混淆密码,但您至少可以防止某些应用程序清理保管库中的所有密码并获取您的密码。