Python中如何实现密码验证?两种方法

2021年3月29日14:20:04 发表评论 983 次浏览

让我们以字母数字字符和特殊字符的组合形式输入密码, 并借助一些条件来检查密码是否有效。

有效密码的条件是:

  1. 应该至少有一个数字。
  2. 应至少包含一个大写字母和一个小写字母。
  3. 应该至少有一个特殊符号。
  4. 长度应在6到20个字符之间。
Input :  Geek12#
Output : Password is valid.

Input :  asd123
Output : Invalid Password !!

我们可以使用多种方式来检查给定的字符串是否符合密码要求。

方法1:天真的方法(不使用正则表达式)。

# Password validation in Python
# using naive method
  
# Function to validate the password
def password_check(passwd):
      
     SpecialSym = [ '$' , '@' , '#' , '%' ]
     val = True
      
     if len (passwd) < 6 :
         print ( 'length should be at least 6' )
         val = False
          
     if len (passwd) > 20 :
         print ( 'length should be not be greater than 8' )
         val = False
          
     if not any (char.isdigit() for char in passwd):
         print ( 'Password should have at least one numeral' )
         val = False
          
     if not any (char.isupper() for char in passwd):
         print ( 'Password should have at least one uppercase letter' )
         val = False
          
     if not any (char.islower() for char in passwd):
         print ( 'Password should have at least one lowercase letter' )
         val = False
          
     if not any (char in SpecialSym for char in passwd):
         print ( 'Password should have at least one of the symbols $@#' )
         val = False
     if val:
         return val
  
# Main method
def main():
     passwd = 'Geek12@'
      
     if (password_check(passwd)):
         print ( "Password is valid" )
     else :
         print ( "Invalid Password !!" )
          
# Driver Code        
if __name__ = = '__main__' :
     main()

输出如下:

Password is valid

此代码使用布尔函数检查是否满足所有条件。我们看到, 尽管代码的复杂性是基本的, 但长度却相当可观。

方法2:使用正则表达式

compile方法()在Regex模块中,该方法创建一个Regex对象, 从而可以将regex函数执行到拍变量。然后我们检查是否由拍后跟输入字符串密码。如果是这样, 则搜索方法返回true, 这将使密码有效。

# importing re library
import re
  
def main():
     passwd = 'Geek12@'
     reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!#%*?&]{6, 20}$"
      
     # compiling regex
     pat = re. compile (reg)
      
     # searching regex                 
     mat = re.search(pat, passwd)
      
     # validating conditions
     if mat:
         print ( "Password is valid." )
     else :
         print ( "Password invalid !!" )
  
# Driver Code     
if __name__ = = '__main__' :
     main()

输出如下:

Password is valid.

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: