鱼C论坛

 找回密码
 立即注册
查看: 1400|回复: 0

[作品展示] 随机密码字符生成程序

[复制链接]
发表于 2018-1-12 19:41:58 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
《零基础入门学习Python》前50课视频看完至今差不多有个把月了,这个周末想起来做一个<密码生成器工具程序>来将目前学到的东西运用一下,采用函数式编程,并且使用了pickle、time、os.path和random四个模块来实现密码和用户数据的读取、保存(标记时间戳),纯粹是按照自己的一点念头打发时间而已,估计很多不足的地方,连同注释有200多行,也是学习小甲鱼视频为止编写的最长的程序了。代码如下,有高手可以指点一下,目前没有详细调试,约摸运行了一下,没发现错误就发出来了,也是为了完成第38课课后作业,提交一个自己的作品,请指教。
  1. # -*- coding: utf-8 -*-
  2. #
  3. # 程序CipherFactory.py
  4. """
  5. # |-----    CipherFactory小程序用于生成 "多位数无规律密码字符串    -----|"
  6. #
  7. # 注明:分别导入了pickle模块、os.path模块、random模块和time模块
  8. #
  9. # 1. pickle模块用于将用户数据以二进制格式存储到本地文件系统
  10. #
  11. # 2. os.path模块用于创建、读取和搜索本地文件
  12. #
  13. # 3. time模块用来生成密码的时间戳



  14. # |-----    各函数组件用途说明    -----|"
  15. #
  16. # 1. password_generate()函数用于生成并返回特定位数的无规则密码字符串
  17. #
  18. # 2. user_ui()函数用于描述注册用户的使用界面的功能选项
  19. #
  20. # 3. new_user_ui()函数用于描述新用户在初次使用的程序接口
  21. #
  22. # 4. read_register()函数用于读取本地注册信息,验证注册用户
  23. #
  24. # 5. whether_read_cipher()函数用于显示用户操作生成过的所有密码字符串
  25. #
  26. # 6. get_localtime()函数用于标记密码字符串生成时的时间戳
  27. #
  28. # 7. whether_save_cipher()函数用于为新用户保存密码
  29. #
  30. # 8. save_user_information()函数用于为新用户创建本地注册信息并写入注册文件
  31. """

  32. import pickle
  33. import os.path
  34. import random as r
  35. import time as tm


  36. def password_generate():
  37.     """按照指定位数生成字母、数字混合而成的密码(不分大小写)"""
  38.    
  39.     while True:
  40.         cipher_bit = input("请输入密码位数 [In]:")
  41.         if cipher_bit.isdigit():
  42.             cipher_bit = int(cipher_bit)
  43.             break
  44.         else:
  45.             print("Input Error.请重新输入!")
  46.             continue
  47.     # 密码所用原始字符集合
  48.     pwd_str = "0123456789abcdefghijklmnopqrstuvwxyz"

  49.     # 待重组的密码字符集
  50.     new_str = ""

  51.     # 最后生成的用户密码
  52.     user_cipher = ""
  53.    
  54.     # 采用类似费雪耶茨算法打乱原始密码字符串
  55.     #
  56.     # 每次循环产生一个随机的索引值,然后以索引值为断点切片重组psw_str原始字符集;
  57.     #
  58.     # 原始字符集有多少个字符就循环多少次,以此打乱全部字符的相对位置
  59.     #
  60.     # 以重组后的新字符串作为密码生成器,生成指定位数的密码;
  61.     #
  62.     # 生成完毕,返回指定位数的用户密码的字符串
  63.     loop = len(pwd_str)
  64.     while loop:
  65.         point = r.randint(0, len(pwd_str)-1)
  66.         new_str = pwd_str[point:] + pwd_str[0:point]
  67.         loop -= 1
  68.    
  69.     while cipher_bit:
  70.         user_cipher += r.choice(new_str)
  71.         cipher_bit -= 1
  72.     return user_cipher


  73. def user_ui():
  74.     """注册用户登陆选项界面"""

  75.     ui_describe = "\n\n==== *  欢迎使用CipherFactory小程序 * ====\n"
  76.     ui_describe += "\n-- 1.用户登陆(Enter:'u')"
  77.     ui_describe += "\n-- 2.用户注册(Enter:'r')"
  78.     ui_describe += "\n-- 3.密码生成(Enter:'p')"
  79.     ui_describe += "\n-- 4.退出程序(Enter:'q')"
  80.     ui_describe += "\n请选择 >>> "
  81.     print(ui_describe, end="")
  82.     register_user_choice = input()
  83.     return register_user_choice


  84. def new_user_ui():
  85.     """新用户登陆选项界面"""

  86.     new_ui_describe = "\n\n==== *  欢迎使用CipherFactory小程序 * ====\n"
  87.     new_ui_describe += "\n-- 密码生成(Enter:'p')"
  88.     new_ui_describe += "\n-- 退出程序(Enter:'q')"
  89.     new_ui_describe += "\n请选择 >>> "
  90.     print(new_ui_describe, end="")
  91.     new_user_choice = input()
  92.     return new_user_choice


  93. def get_localtime():
  94.     """为生成的密码标记时间戳"""
  95.    
  96.     # 首先调用time.time()生成1970年至今的时间间隔秒数
  97.     time_interval = tm.time()
  98.    
  99.     # 然后用time.localtime()方法将时间间隔转换成本地时间
  100.     local_time = tm.localtime(time_interval)
  101.    
  102.     # 最后用time.strftime()方法格式化本地时间,形成格式化时间戳
  103.     time_stamp = tm.strftime("%Y-%m-%d <%H:%M:%S>", local_time)
  104.    
  105.     # 返回时间戳
  106.     return time_stamp
  107.       


  108. def whether_save_cipher(user_pwd, time_stamp):
  109.     """将生成的密码通过pickle模块保存到本地usercipher.plk文件"""
  110.    
  111.     # 用于存储用户密码的.pkl文件
  112.     file_name = "usercipher.pkl"
  113.    
  114.     # 将密码字符串和时间戳存储为字典格式
  115.     pwd_information = {}
  116.     pwd_information["密码Cipher"] = user_pwd
  117.     pwd_information["时间Time"] = time_stamp
  118.    
  119.     # 创建本地pkl文件并保存密码和生成时间两项信息
  120.     try:
  121.         with open(file_name, "ab") as pickle_file_object:
  122.             pickle.dump(pwd_information, pickle_file_object)
  123.     except OSError:
  124.         print(" ---> 内容未能写入指定文件 <--- ")


  125. def whether_read_cipher():
  126.     """读取本地usercipher.pkl文件,显示所有已保存的历史密码字符串"""
  127.    
  128.     file_name = "usercipher.pkl"
  129.     with open(file_name, "rb") as file_object:
  130.         try:
  131.             while True:
  132.                 pwd_information = pickle.load(file_object)
  133.                 if pwd_information:
  134.                     print("% 23s" % pwd_information["密码Cipher"], end="")
  135.                     print("% 23s" % pwd_information["时间Time"])
  136.                     continue
  137.                 else:
  138.                     break
  139.         except EOFError:
  140.             print("===================   End   ===================")


  141. def save_user_information(user_name):
  142.     """
  143.     # 根据新用户输入的用户名创建本地注册文件,实现登陆操作
  144.     # 以字典格式保存注册用户信息;
  145.     """
  146.    
  147.     user_information = {}
  148.     user_information["用户名"] = user_name
  149.     user_access = input("请输入今后的访问密码[In]:")
  150.     user_information["访问密码"] = user_access
  151.     try:
  152.         with open("register_user_list.pkl", "ab") as rfile:
  153.             pickle.dump(user_information, rfile)
  154.             print("您的信息已保存完毕 >>> ")
  155.     except OSError:
  156.         print("未知原因,注册失败......")


  157. def read_register():
  158.     """读取本地注册文件,获得注册用户数据"""

  159.     try:
  160.         with open("register_user_list.pkl", "rb") as rfile:
  161.             user_information = pickle.load(rfile)
  162.             
  163.     except FileNotFoundError:
  164.         print("用户文件被破坏,无法读取用户信息...")
  165.     user_name = user_information["用户名"]
  166.     user_pwd = user_information["访问密码"]

  167.     # 返回读取到的文件内容
  168.     return user_name, user_pwd
  169.             
  170.    
  171. """以下为主程序部分,调用函数实现既定功能"""
  172. while True:
  173.     # 调用generate_function模块中的user_ui函数,显示用户界面
  174.     if os.path.isfile("register_user_list.pkl"):
  175.         register_user_choice = user_ui()
  176.         # 根据用户的输入完成指定任务
  177.         if register_user_choice == "q":
  178.             break

  179.         # 生成随机密码,并询问用户是否保存
  180.         elif register_user_choice == "p":
  181.             user_pwd = password_generate()
  182.             print("\n-- 密码已生成 >>> " + "[ " + user_pwd + " ]\n")
  183.             save_choice = input("是否保存密码序列?(Y / N):")
  184.             if save_choice == "Y" or save_choice == "y":
  185.                 time_stamp = get_localtime()
  186.                 whether_save_cipher(user_pwd, time_stamp)
  187.                 continue
  188.             else:
  189.                 print("密码未保存,请继续......")
  190.                 continue

  191.         # 进入用户登陆验证操作,读取本地注册文件,以便验证用户真伪
  192.         elif register_user_choice == "u":
  193.             register_user_information = read_register()
  194.             while True:
  195.                 input_user_name = input("请输入您的用户名:")

  196.                 # 验证输入的用户名和本地注册用户名是否相同
  197.                 if input_user_name != register_user_information[0]:
  198.                     print("警告!>>> 用户名错误,请重新输入......")
  199.                     continue
  200.                 else:
  201.                     # 如果用户名正确,则验证用户密码
  202.                     while True:
  203.                         input_user_pwd = input("请输入您的密码:")
  204.                         if input_user_pwd != register_user_information[1]:
  205.                             print("密码错误,请重新输入:")
  206.                             continue
  207.                         else:
  208.                             print("验证通过,进入程序......")
  209.                             print("==================< 历史纪录 >==================")
  210.                             whether_read_cipher()
  211.                             break
  212.                     break
  213.         elif register_user_choice == "r":
  214.             print("come soon.\n")
  215.             continue

  216.     # 如果是首次运行本程序,则调用new_user_ui()函数显示新用户界面
  217.     else:
  218.         new_user_choice = new_user_ui()
  219.         if new_user_choice == "q":
  220.             break
  221.         elif new_user_choice == "p":
  222.             user_pwd = password_generate()
  223.             print("\n-- 密码已生成 >>> " + "[ " + user_pwd + " ]\n")
  224.             save_choice = input("是否保存密码序列?(Y / N):")
  225.             if save_choice == "N" or save_choice == "n":
  226.                 continue
  227.             elif save_choice == "Y" or save_choice == "y":
  228.                 message = "请输入一个您喜欢的用户名[键入Q或q退出,将不保存]:"
  229.                 user_name = input(message)
  230.                 if user_name == "Q" or user_name == "q":
  231.                     break
  232.                 else:
  233.                     save_user_information(user_name)
  234.                     time_stamp = get_localtime()
  235.                     whether_save_cipher(user_pwd, time_stamp)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-17 00:43

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表