美文网首页
案例(6):判断密码强弱

案例(6):判断密码强弱

作者: hwang_zhic | 来源:发表于2019-03-14 02:24 被阅读0次

    本章通过判断密码强弱的6个案例来进行学习基础的Python程序

    案例描述

    密码强度:是指一个密码对抗猜测或时暴力破解的有效程度;一般是
    1.指一个未授权的访问者得到正确密码的平均尝试次数
    2.强密码可以降低安全漏洞的整体风险
    3.简易版(常用)规则:(1)密码长度至少8位;(2)密码含有数字;(3)密码含有字母

    案例分析

    根据以下函数判断密码强度并输出:
    1.设置一个变量strength_level用于记录密码的强度,初始为0。满足一个条件,对其加1;
    2.长度判断:使用len()方法;
    3.包含数字判断:对密码字符串遍历,使用isnumeric()方法;
    4.包含字母判断:对密码字符串遍历,使用isalpha()方法;
    5.如果strength_level等于3,密码强度合格,否则不合格

    v1.0

    新建一个简单的Python程序,将判断是否有数字和字幕的语句分别封装成2个函数,调用函数时传递密码,返回结果,若有则返回True,否则False。
    主函数则实现用户输入密码,初始化密码强度,依次判断长度、字母、数字,最后根据密码强度stength_level判断密码是否合格并输出结果。

    知识点:

    1.Python字符串
    (1)str.isnumeric():检测字符串是否只由数字组成
    (2)str.isalpha():检测字符串是否只由字母组成
    (3)str.islower():检测字符串中所有的字母是否都为小写
    (4)str.isupper():检测字符串中所有的字母是否都为大写


    PS:更多isxxx()方法请参考:https://docs.python.org/3/library/stdtypes.html#string-methods

    判断函数:

    def check_num_exist(passwd_input):
        """
            检查字符串是否有数字,有就返回true
        """
        for c in passwd_input:
            if c.isnumeric():
                return True
        return False
    
    def check_letter_exist(passwd_input):
        """
            检查字符串是否有字母,有就返回true
        """
        for c in passwd_input:
            if c.isalpha():
                return True
        return False
    

    主体代码:

    def main():
        """
            主函数
        """
        # 输入密码
        passwd_input = input("请输入密码:")
        # 密码强度
        stength_level = 0
        # 判断密码长度
        if len(passwd_input) > 8:
            stength_level += 1
        else:
            print("输入的密码不够长!")
        # 判断密码是否有数字,然后操作
        if check_num_exist(passwd_input):
            stength_level += 1
        else:
            print("输入的密码没有数字!")
        # 判断密码是否有字母,然后操作
        if check_letter_exist(passwd_input):
            stength_level += 1
        else:
            print("输入的密码没有字母!")
        # 输出结果——密码强度
        if stength_level >= 3:
            print("恭喜!输入的密码合格!")
        else:
            print("输入的密码不合格!")
    

    结果如图所示:

    合格图
    不合格

    v2.0

    在v1.0的基础上,2.0增加功能:限制密码设置次数;循环的终止。当用户在规定次数内设置符合要求的密码,则使用continue语句或者break语句终止循环。循环使用while,通过判断 try_times是否达到5次来判断是否继续,若超过次数则提示次数过多。若密码合格也中断循环,符合日常使用,中断使用break。

    知识点:

    1.循环的终止:
    (1)break语句:终止整个循环
    (2)continue语句:只终止本次循环,而不终止整个循环的执行

    循环终止操作示例:


    判断函数:

    def check_num_exist(passwd_input):
        """
            检查字符串是否有数字,有就返回true
        """
        has_number = False
        for c in passwd_input:
            if c.isnumeric():
                has_number = True
        return has_number
    
    def check_letter_exist(passwd_input):
        """
            检查字符串是否有字母,有就返回true
        """
        has_letter = False
        for c in passwd_input:
            if c.isalpha():
                has_letter = True
        return has_letter
    

    具体代码:

    def main():
        """
            主函数
        """
        # 密码循环设置次数
        try_times = 5
        while try_times > 0:
            # 输入密码
            passwd_input = input("请输入密码:")
            # 密码强度
            stength_level = 0
            # 判断密码长度
            if len(passwd_input) > 8:
                stength_level += 1
            else:
                print("输入的密码要求长度过8位!")
            # 判断密码是否有数字,然后操作
            if check_num_exist(passwd_input):
                stength_level += 1
            else:
                print("输入的密码要求包含数字!")
            # 判断密码是否有字母,然后操作
            if check_letter_exist(passwd_input):
                stength_level += 1
            else:
                print("输入的密码要求包含字母!")
            # 输出结果——密码强度
            if stength_level >= 3:
                print("恭喜!输入的密码合格!")
                break
            else:
                print("输入的密码不合格!请重新输入!")
                try_times -= 1
                print()
    
        if try_times <= 0:
            print("尝试次数过多,终止密码设置!")
    
    运行结果:

    v3.0

    在2.0的基础上,3.0增加功能:保存设置的密码及其对应的强度到文件中。文件操作需要先用open()打开,然后写入模式使用“a”避免覆盖。每次写入完成后都用户close()关闭。其他细节与上一案例一致。

    知识点:

    1.文件的基础
    (1)文件:存储在外部介质(如:硬盘)上的数据或信息的集合
    (2)文本文件:一般指只有字符编码存储的文件,能够被最简单的文本编辑器直接读取
    (3)编码:信息从一种形式转换为另一种形式的过程;常用的编码:ASCII, Unicode, UTF-8…
    (4)多行文本,用 \n 表示换行
    2.文件的操作
    (1)步骤:打开文件 -> 操作文件(读、写等)-> 关闭文件
    (2)

    1. 打开文件:建立文件与程序的关联:
      • open(filename, mode);filename:文件名(包括路径);mode: 打开模式
    2. 操作文件:写入,读取,等
      • 写入操作:从计算机内存向文件写入数据
      • write(): 将文本数据写入文件中
      • writelines(): 将字符串列表写入文件中
    3. 关闭文件:终止程序与文件的关联
      • close()

    PS:文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的。
    具体文件操作参考链接:https://www.cnblogs.com/xinchrome/p/5011304.html


    例子主要代码如下:

    def check_num_exist(passwd_input):
        """
            检查字符串是否有数字,有就返回true
        """
        has_number = False
        for c in passwd_input:
            if c.isnumeric():
                has_number = True
        return has_number
    
    def check_letter_exist(passwd_input):
        """
            检查字符串是否有字母,有就返回true
        """
        has_letter = False
        for c in passwd_input:
            if c.isalpha():
                has_letter = True
        return has_letter
    
    def main():
        """
            主函数
        """
        # 密码循环设置次数
        try_times = 5
        while try_times > 0:
            # 输入密码
            passwd_input = input("请输入密码:")
            # 密码强度
            stength_level = 0
    
            # 判断密码长度
            if len(passwd_input) > 8:
                stength_level += 1
            else:
                print("输入的密码要求长度过8位!")
            # 判断密码是否有数字,然后操作
            if check_num_exist(passwd_input):
                stength_level += 1
            else:
                print("输入的密码要求包含数字!")
            # 判断密码是否有字母,然后操作
            if check_letter_exist(passwd_input):
                stength_level += 1
            else:
                print("输入的密码要求包含字母!")
    
            f = open("password_v3.0.txt", "a")
            f.write("密码:{},强度:{}\n".format(passwd_input, stength_level))
            f.close()
    
            # 输出结果——密码强度
            if stength_level >= 3:
                print("恭喜!输入的密码合格!")
                break
            else:
                print("输入的密码不合格!请重新输入!")
                try_times -= 1
                print()
    
        if try_times <= 0:
            print("尝试次数过多,终止密码设置!")
    

    代码部分运行结果:


    图1
    图2

    v4.0

    在v3.0的基础上,4.0增加功能:读取保存的密码。文件读取操作分3种:read()、readline()、readlines(),具体作用如下所示。

    知识点:

    1.文件的操作
    (1)读取操作:从文件中读取数据到计算机内存中
    (2)read(): 返回值为包含整个文件内容的一个字符串
    (3)readline(): 返回值为文件下一行内容的字符串
    (4)readlines(): 返回值为整个文件内容的列表,每项是以换行符为结尾的一行字符串
    (5)文件的遍历


    主要代码:

    # 密码循环设置次数
        try_times = 5
        while try_times > 0:
            # 输入密码
            passwd_input = input("请输入密码:")
            # 密码强度
            stength_level = 0
    
            # 判断密码长度
            if len(passwd_input) > 8:
                stength_level += 1
            else:
                print("输入的密码要求长度过8位!")
            # 判断密码是否有数字,然后操作
            if check_num_exist(passwd_input):
                stength_level += 1
            else:
                print("输入的密码要求包含数字!")
            # 判断密码是否有字母,然后操作
            if check_letter_exist(passwd_input):
                stength_level += 1
            else:
                print("输入的密码要求包含字母!")
    
            f = open("password_v4.0.txt", "a")
            f.write("密码:{},强度:{}\n".format(passwd_input, stength_level))
            f.close()
    
            # 输出结果——密码强度
            if stength_level >= 3:
                print("恭喜!输入的密码合格!")
                break
            else:
                print("输入的密码不合格!请重新输入!")
                try_times -= 1
                print()
    
        if try_times <= 0:
            print("尝试次数过多,终止密码设置!")
    
        f = open("password_v3.0.txt", "r")
        # 1.read()
        # content = f.read()
        # print(content)
    
        # 2.readline()
        # line = f.readline()
        # print(line)
        # line = f.readline()
        # print(line)
    
        # 3.readlines()
        lines = f.readlines()
        print(lines)
        for l in lines:
            print(l)
    
        f.close()
    

    执行结果:


    v5.0

    在v4.0的基础上,5.0增加功能:将相关方法封装成一个整体:面向对象编程。因为Python是面向对象语言,所以可以将密码操作封装成一个工具类,方法包含判断是否有数字、字母和输出密码强度。主函数可以直接创建一个密码类的对象,然后进行相应的处理。

    知识点:

    1.面向过程vs面向对象
    (1)面向过程(POP):以程序执行过程为设计流程的编程思想
    (2)面向对象(OOP):以事物为中心的编程思想
    (3)现实世界中的对象:属性,行为
    • 对象例子:
    • 波斯猫,属性:品种、颜色、大小;行为:叫、捉老鼠
    • 吉普车,属性:类型、用途;行为:发动、停车
    2.类(class):某种类型集合的描述
    (1)属性:类本身的一些特性
    (2)方法:类所能实现的行为
    (3)类的定义:
    class ClassName
    init(self)构造函数:初始化对象的各属性,可以传参数进来
    self代表类的实例:属性和方法的调用

    类的创建示例:


    PS:总结:http://www.runoob.com/python/python-object.html

    密码类代码:

    class Password_tool:
        def __init__(self, password):
            self.password = password
            self.stength_level = 0
    
        def check_num_exist(self):
            """
                检查字符串是否有数字,有就返回true
            """
            has_number = False
            for c in self.password:
                if c.isnumeric():
                    has_number = True
            return has_number
    
        def check_letter_exist(self):
            """
                检查字符串是否有字母,有就返回true
            """
            has_letter = False
            for c in self.password:
                if c.isalpha():
                    has_letter = True
            return has_letter
    
        def passwd_process(self):
            # 判断密码长度
            if len(self.password) > 8:
                self.stength_level += 1
            else:
                print("输入的密码要求长度过8位!")
            # 判断密码是否有数字,然后操作
            if self.check_num_exist():
                self.stength_level += 1
            else:
                print("输入的密码要求包含数字!")
            # 判断密码是否有字母,然后操作
            if self.check_letter_exist():
                self.stength_level += 1
            else:
                print("输入的密码要求包含字母!")
    

    主函数代码

    # 密码循环设置次数
        try_times = 5
        while try_times > 0:
            # 输入密码
            passwd_input = input("请输入密码:")
    
            # 实例化密码工具对象
            password_tool = Password_tool(passwd_input)
            password_tool.passwd_process()
    
            f = open("password_v5.0.txt", "a")
            f.write("密码:{},强度:{}\n".format(passwd_input, password_tool.stength_level))
            f.close()
    
            # 输出结果——密码强度
            if password_tool.stength_level >= 3:
                print("恭喜!输入的密码合格!")
                break
            else:
                print("输入的密码不合格!请重新输入!")
                try_times -= 1
                print()
    
        if try_times <= 0:
            print("尝试次数过多,终止密码设置!")
    
        f = open("password_v5.0.txt", "r")
        # 3.readlines()
        lines = f.readlines()
        print(lines)
        for l in lines:
            print(l)
        f.close()
    

    执行结果:


    v6.0

    在v5.0的基础上,6.0增加功能:将文件操作封装到一个类中。这里和密码类一样,新建一个文件操作的类,把读和写操作,参数是文件路径。

    知识点:

    1.面向对象的特点
    (1)封装
    • 将数据及相关操作打包在一起
    • 支持代码复用
    (2)继承
    • 子类(subclass)借用父类(superclass)的行为
    • 避免重复操作,提升代码复用程度
    • 定义 class ClassName(SuperClassName)
    (3)多态
    • 在不同情况下用一个函数名启用不同方法
    • 灵活性

    具体示例参考:https://blog.csdn.net/qq_29287973/article/details/77868474
    密码类代码:

    class Password_tool:
        def __init__(self, password):
            self.password = password
            self.stength_level = 0
    
        def check_num_exist(self):
            """
                检查字符串是否有数字,有就返回true
            """
            has_number = False
            for c in self.password:
                if c.isnumeric():
                    has_number = True
            return has_number
    
        def check_letter_exist(self):
            """
                检查字符串是否有字母,有就返回true
            """
            has_letter = False
            for c in self.password:
                if c.isalpha():
                    has_letter = True
            return has_letter
    
        def passwd_process(self):
            # 判断密码长度
            if len(self.password) > 8:
                self.stength_level += 1
            else:
                print("输入的密码要求长度过8位!")
            # 判断密码是否有数字,然后操作
            if self.check_num_exist():
                self.stength_level += 1
            else:
                print("输入的密码要求包含数字!")
            # 判断密码是否有字母,然后操作
            if self.check_letter_exist():
                self.stength_level += 1
            else:
                print("输入的密码要求包含字母!")
    

    文件操作类

    class File_tool:
        """
            文件操作类
        """
    
        def __init__(self, filepath):
            self.filepath = filepath
    
        def write_to_file(self, line):
            f = open(self.filepath, "a")
            f.write(line)
            f.close()
    
        def read_from_file(self):
            f = open(self.filepath, "r")
            lines = f.readlines()
            f.close()
            return lines
    

    主要代码

    # 密码循环设置次数
        try_times = 5
        filepath = "password_v6.0.txt"
        file_tool = File_tool(filepath)
        while try_times > 0:
            # 输入密码
            passwd_input = input("请输入密码:")
    
            # 实例化密码工具对象
            password_tool = Password_tool(passwd_input)
            password_tool.passwd_process()
    
            line = "密码:{},强度:{}\n".format(passwd_input, password_tool.stength_level)
            file_tool.write_to_file(line)
    
            # 输出结果——密码强度
            if password_tool.stength_level >= 3:
                print("恭喜!输入的密码合格!")
                break
            else:
                print("输入的密码不合格!请重新输入!")
                try_times -= 1
                print()
    
        if try_times <= 0:
            print("尝试次数过多,终止密码设置!")
    
        contents = file_tool.read_from_file()
        print(contents)
    

    执行结果:


    总结

    判断密码强弱的6个例子,知识点归纳如下:


    完整代码查看码云

    相关文章

      网友评论

          本文标题:案例(6):判断密码强弱

          本文链接:https://www.haomeiwen.com/subject/tnwdyqtx.html