Python 在明文文件中加密密码的最佳方法

Python best way to encrypt password in clear file

我正在寻找一种从用户那里获取密码但安全性很好的方法。

目前,我在yaml文件中这样写用户密码:

---
app:
  username: tata
  password: toto

使用 python 的代码:

 url = http://application.com
 username = Cfg.get(['app', 'username'])
 password = Cfg.get(['app', 'password'])
 auth = Appli(url, username, password)

但不是很干净,我不想用 base64 函数加密到 base64

不太清楚你要解决什么问题。

您可以使用 pycrypto 来加密或解密您的数据,任何现代算法都可以。真正的问题是,如果您需要以编程方式访问加密数据,您应该如何存储密钥。存储加密数据+密钥真的能解决您的安全问题吗?

旁注:您可能会发现 this old blog post 有用

有很多 pythonic 方法可以做到这一点。 您还可以仅将密码存储在数据库级别的哈希中,例如 SHA1md5SHA256

当用户输入his/her密码时,系统会将其转换为hash(您选择的hash算法),然后与数据库的hash算法进行校验,判断输入的密码是否正确。

import hashlib

url = http://application.com
username = Cfg.get(['app', 'username'])

password= Cfg.get(['app', 'password'])

#store pass_hash in the database
pass_hash= hashlib.sha256(password.encode()).hexdigest()

#authenticate using pass_hash not the actual textual password
auth = Appli(url, username, pass_hash)

在这种情况下,即使您的数据库暴露给外部人员,您的实际密码也是安全的,只有哈希值是可见的。