在现代网络生活中,我们经常需要记住多个账户密码,如邮箱、社交媒体、银行账户等。为了安全起见,我们不应使用相同的密码或过于简单的密码,这无疑增加了记忆的难度。同时,密码遗忘也是一个常见的问题。本文将介绍...
在现代网络生活中,我们经常需要记住多个账户密码,如邮箱、社交媒体、银行账户等。为了安全起见,我们不应使用相同的密码或过于简单的密码,这无疑增加了记忆的难度。同时,密码遗忘也是一个常见的问题。本文将介绍如何使用Python实现账户密码的本地安全存储,帮助用户轻松管理密码,并有效解决密码遗忘的烦恼。
本项目旨在使用Python编写一个简单的密码管理器,其主要功能包括:
密码信息将使用加密算法进行加密存储,以确保用户数据的安全。
首先,需要安装以下Python库:
cryptography:用于密码加密和解密getpass:用于安全地获取用户输入的密码可以通过以下命令安装这些库:
pip install cryptography getpass我们将使用字典(dict)来存储密码信息,其中每个条目的键是账户名称,值是另一个字典,包含密码的明文和加密后的密文。
passwords = { "Gmail": { "plaintext": "mygmailpassword", "ciphertext": "encryptedpasswordhere" }, "Blog": { "plaintext": "myblogpassword", "ciphertext": "encryptedpasswordhere" }, # 其他账户...
}使用cryptography库提供的加密算法对密码进行加密和解密。
from cryptography.fernet import Fernet
# 生成密钥
key = Fernet.generate_key()
# 创建Fernet对象
cipher_suite = Fernet(key)
# 加密密码
def encrypt_password(password): return cipher_suite.encrypt(password.encode())
# 解密密码
def decrypt_password(ciphertext): return cipher_suite.decrypt(ciphertext).decode()def add_new_password(account, password): encrypted_password = encrypt_password(password) passwords[account] = { "plaintext": password, "ciphertext": encrypted_password }def show_all_passwords(): for account, password_info in passwords.items(): print(f"{account}: {decrypt_password(password_info['ciphertext'])}")def find_password(account): if account in passwords: print(f"{account}: {decrypt_password(passwords[account]['ciphertext'])}") else: print("Account not found.")def update_password(account, new_password): if account in passwords: passwords[account]["plaintext"] = new_password passwords[account]["ciphertext"] = encrypt_password(new_password) print("Password updated successfully.") else: print("Account not found.")def delete_password(account): if account in passwords: del passwords[account] print("Password deleted successfully.") else: print("Account not found.")可以使用简单的命令行界面来实现用户交互。
def main(): while True: print("\nPassword Manager") print("1. Add new password") print("2. Show all passwords") print("3. Find password") print("4. Update password") print("5. Delete password") print("6. Exit") choice = input("Enter your choice: ") if choice == "1": account = input("Enter account name: ") password = getpass.getpass("Enter password: ") add_new_password(account, password) elif choice == "2": show_all_passwords() elif choice == "3": account = input("Enter account name: ") find_password(account) elif choice == "4": account = input("Enter account name: ") new_password = getpass.getpass("Enter new password: ") update_password(account, new_password) elif choice == "5": account = input("Enter account name: ") delete_password(account) elif choice == "6": break else: print("Invalid choice. Please try again.")
if __name__ == "__main__": main()通过以上步骤,我们可以实现一个简单的密码管理器,帮助用户安全地存储和管理账户密码,并有效解决密码遗忘的烦恼。在实际应用中,还可以进一步优化和完善该密码管理器,如增加密码强度验证、支持多种加密算法等。