password_handle.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import asyncio
  2. import random
  3. import string
  4. from cryptography.fernet import Fernet
  5. from app.config.config import settings
  6. cipher_suite = Fernet(settings.PASSWORD_KEY.encode("utf-8"))
  7. async def generate_password(length=10):
  8. if length < 6: # 至少需要3位密码以包含所有必要的字符
  9. raise ValueError("Password length should be at least 3")
  10. # 确保密码中至少包含一个字母和一个数字
  11. password = [
  12. random.choice(string.ascii_uppercase), # 大写字母
  13. random.choice(string.ascii_lowercase), # 小写字母
  14. random.choice(string.digits) # 数字
  15. ]
  16. # 添加剩余的随机字符
  17. characters = string.ascii_letters + string.digits
  18. password.extend(random.choice(characters) for _ in range(length - 3))
  19. # 打乱密码以确保随机性
  20. random.shuffle(password)
  21. # 将列表转换为字符串
  22. return ''.join(password)
  23. async def password_encrypted(password):
  24. hash_pwd = cipher_suite.encrypt(password.encode("utf-8")).decode("utf-8")
  25. # print(hash_pwd)
  26. return hash_pwd
  27. async def password_decrypted(hash_password):
  28. pwd = cipher_suite.decrypt(hash_password).decode("utf-8")
  29. # print(pwd)
  30. return pwd
  31. if __name__ == "__main__":
  32. # 生成一个10位的密码
  33. # asyncio.run(generate_password(10))
  34. # password = generate_password(10)
  35. # print(password)
  36. asyncio.run(password_encrypted("zhaoqg123456"))
  37. asyncio.run(password_decrypted("gAAAAABnh2Y-OYrpdm2QuW24j4QL3pxjkKZsHu37Vzl_mh8SrG5Roa5TThcBxcj7hqPq7NrA8OaL0WdsmpcpYDfpZCofBVjbbA=="))