如何在Python 3.x中创建无法被记事本读取的密码存储文件?
解决密码明文存储的安全问题
Hey there! I get exactly why you're frustrated—storing passwords in plaintext (even in a .bin file) is a huge security risk, since any text editor can just read them right away. Let's fix this with two practical Python 3.x approaches that'll make your password storage unreadable to Notepad or similar tools:
方法1:使用密码哈希(推荐用于纯验证场景)
如果你的程序只需要验证密码是否正确(不需要还原出原始明文密码),哈希是最优解。哈希函数会把密码转换成一串固定长度的乱码,而且不可逆—你没法从哈希值还原出原密码,只能比对输入密码的哈希和存储的哈希是否一致。
步骤示例(用bcrypt库,安全性高)
- 先安装bcrypt:
pip install bcrypt
- 存储密码的哈希值:
import bcrypt # 要存储的原始密码(注意要转成bytes类型) password = b"my_secure_password123" # 生成随机盐值并哈希密码 salt = bcrypt.gensalt() hashed_password = bcrypt.hashpw(password, salt) # 将哈希值写入文件(.dat或.bin格式都适用) with open("password_hash.dat", "wb") as f: f.write(hashed_password)
- 验证密码时读取比对:
import bcrypt # 获取用户输入的密码(转成bytes) user_input = b"user_entered_password" # 读取存储的哈希值 with open("password_hash.dat", "rb") as f: stored_hash = f.read() # 比对哈希值判断密码是否正确 if bcrypt.checkpw(user_input, stored_hash): print("密码验证通过!") else: print("密码错误!")
打开这个.dat文件,你只会看到一堆毫无意义的乱码,完全看不到原始密码。
方法2:对称加密(需要还原明文密码的场景)
如果你的程序必须要取出原始明文密码(比如用来自动登录其他服务),可以用对称加密:用一个密钥把密码加密后存储,读取时再用同一个密钥解密。
步骤示例(用cryptography库的Fernet)
- 先安装cryptography:
pip install cryptography
- 生成密钥(注意:密钥要妥善保存,别硬编码在代码里!可以存在环境变量或单独的安全文件中):
from cryptography.fernet import Fernet # 生成密钥(只需要做一次,生成后务必保存好) key = Fernet.generate_key() with open("secret_key.key", "wb") as f: f.write(key)
- 加密并存储密码:
from cryptography.fernet import Fernet # 读取密钥 with open("secret_key.key", "rb") as f: key = f.read() cipher = Fernet(key) password = b"my_secure_password123" encrypted_password = cipher.encrypt(password) # 写入加密后的内容到文件 with open("encrypted_password.dat", "wb") as f: f.write(encrypted_password)
- 读取并解密密码:
from cryptography.fernet import Fernet # 读取密钥 with open("secret_key.key", "rb") as f: key = f.read() cipher = Fernet(key) # 读取加密后的内容 with open("encrypted_password.dat", "rb") as f: encrypted_data = f.read() # 解密得到原始密码 decrypted_password = cipher.decrypt(encrypted_data) print("原始密码:", decrypted_password.decode())
加密后的.dat文件用记事本打开也是乱码,只有持有密钥的人才能解密出明文。
关键注意事项
- 不要自己瞎写简单加密逻辑(比如手动转ASCII、异或),这些很容易被破解,一定要用成熟的加密库。
- 哈希方法里,一定要用带随机盐值的哈希函数(bcrypt自动处理盐值,非常省心),避免彩虹表攻击。
- 对称加密的密钥绝对不能泄露,也不要和加密文件存放在一起,最好用环境变量或者专门的密钥管理工具。
内容的提问来源于stack exchange,提问作者thefeni
相关产品推荐
相关产品推荐

