在Python中生成随机密码的方法

537 阅读5分钟

在这篇文章中,我们将学习如何在Python中创建一个随机密码发生器。使用一个强大的密码是必要的,而是推荐的。按照网络安全专家的说法,密码必须是字母、数字和符号的组合,还要确保这些组合不构成一个可以用社会工程方法轻易猜到的合理的词或组合。

另一方面,一个长度至少为8个字符的随机密码,即使应用先进的安全漏洞方法,如暴力攻击,也很难突破或破解,或可能需要很长的时间来突破它。

随机密码生成器的代码 - GUI

生成一个推荐长度的强随机密码是一个困难的任务,显然不比记住它更难。但在这里,我们将编写一个python脚本来生成一个随机密码。

1.安装和导入所需的模块

我们首先使用pip软件包管理器安装所需的库。在你的命令行或终端输入以下命令来安装模块。

我们需要安装Tkinter,使我们的密码生成器成为基于GUI(图形用户界面)的pyperclip库,以注入复制到剪贴板的功能。

pip install tkinter
pip install pyperclip
pip install random

从终端安装完所需的库后,我们现在进入我们的Python文件进行编码。我们从导入库开始。

其中random用于从一个给定的列表中生成随机 字符,string 用于获取字符/文本。

import random, string
from tkinter import *
import pyperclip

2.初始化Tkinter窗口

作为下一步,我们使用Tkinter模块初始化我们的GUI窗口。

#Initialize Window

root =Tk()
root.geometry("400x400") #size of the window by default

#title of our window
root.title("Random Password Generator")

3.对元素进行编码

我们现在开始按照GUI的要求对元素进行编码,包括标题、文本、标签、按钮等。

要选择密码的长度

  • 我们使用Label 方法生成一个文本标签来定义我们想要的密码长度的输入域的目的。
  • spinbox 方法被用来对一个值选择器进行输入,范围从4到32,你可以根据需要改变,这定义了密码的最小和最大长度。
#get length of password

pass_head = Label(root, text = 'Password Length', font = 'arial 12 bold').pack(pady=10) #to generate label heading

pass_len = IntVar() #integer variable to store the input of length of the password wanted
length = Spinbox(root, from_ = 4, to_ = 32 , textvariable = pass_len , width = 24, font='arial 16').pack()

我们编写一个 生成密码的按钮,点击它可以生成一个随机密码。

  • 我们给我们的按钮一些造型,以及名称--生成密码。我们使用命令,显示哪个函数(这里是randPassGen函数)将在按钮的点击(按键)中运行。
Button(root, text = "Generate Password" , command = randPassGen, font="Arial 10", bg='lightblue', fg='black', activebackground="teal", padx=5, pady=5 ).pack(pady= 20)

这样添加后,我们现在在代码中添加输出元素。

  • 我们再次添加一个标签,以显示正在显示的内容,我们添加一个 "随机生成的密码 "的标签 ,并加上一些样式。
  • 然而,我们再次添加一个Entry widget来创建一个输入字段,这是为了显示我们的随机生成的密码
  • textvariable 小组件用于显示来自output_pass变量的文本,该变量保存了随机生成的密码。
pass_label = Label(root, text = 'Random Generated Password', font = 'arial 12 bold').pack(pady="30 10")
Entry(root , textvariable = output_pass, width = 24, font='arial 16').pack()

  • 我们现在在代码中添加添加到剪贴板的按钮,它的命令部件显示copyPass函数将在点击该按钮时运行。
Button(root, text = 'Copy to Clipboard', command = copyPass, font="Arial 10", bg='lightblue', fg='black', activebackground="teal", padx=5, pady=5 ).pack(pady= 20)

4.随机密码功能

在完成了前端(GUI)部分后,我们现在转到代码的后端,在那里我们为我们的按钮添加功能

  • 我们对这段代码中最重要的功能进行编码,也就是随机密码生成,我们按照代码中的方法进行。
#Random Password generator

output_pass = StringVar()

all_combi = [string.punctuation, string.ascii_uppercase, string.digits, string.ascii_lowercase]  #list of all possible characters

def randPassGen():
    password = "" # to store password
    for y in range(pass_len.get()):
        char_type = random.choice(all_combi)   #to randomize the occurance of alphabet, digit or symbol
        password = password + random.choice(char_type) #to generate random characters as per the input length from the occurance list
    
    output_pass.set(password)

5.复制密码功能

作为最后一步,我们在代码中添加复制密码的功能。

  • 我们使用pyperclip 库的复制方法来保存复制到我们系统中的密码。我们使用output_pass变量的get方法来获取密码。
#Copy to clipboard function

def copyPass():
    pyperclip.copy(output_pass.get())

虽然在教程中讨论得比较晚,但随机密码生成器和复制到剪贴板的函数并没有包含在代码的最后,因为在这种情况下,如果没有找到,程序将抛出一个错误。

我们在窗口的初始化之后声明我们的函数(在步骤2的代码之后)。正如下面的最终代码所示。

GUI随机密码生成器的完整Python代码

import random, string
from tkinter import *
import pyperclip


#Initialize Window

root =Tk()
root.geometry("400x400") #size of the window by default

#title of our window
root.title("Random Password Generator")

# -------------------  Random Password generator function

output_pass = StringVar()

all_combi = [string.punctuation, string.ascii_uppercase, string.digits, string.ascii_lowercase]  #list of all possible characters

def randPassGen():
    password = "" # to store password
    for y in range(pass_len.get()):
        char_type = random.choice(all_combi)   #to randomize the occurance of alphabet, digit or symbol
        password = password + random.choice(char_type)
    
    output_pass.set(password)

# ----------- Copy to clipboard function

def copyPass():
    pyperclip.copy(output_pass.get())

#-----------------------Front-end Designing (GUI)

pass_head = Label(root, text = 'Password Length', font = 'arial 12 bold').pack(pady=10) #to generate label heading

pass_len = IntVar() #integer variable to store the input of length of the password wanted
length = Spinbox(root, from_ = 4, to_ = 32 , textvariable = pass_len , width = 24, font='arial 16').pack()

#Generate password button

Button(root, command = randPassGen, text = "Generate Password", font="Arial 10", bg='lightblue', fg='black', activebackground="teal", padx=5, pady=5 ).pack(pady= 20)

pass_label = Label(root, text = 'Random Generated Password', font = 'arial 12 bold').pack(pady="30 10")
Entry(root , textvariable = output_pass, width = 24, font='arial 16').pack()

#Copy to clipboard button

Button(root, text = 'Copy to Clipboard', command = copyPass, font="Arial 10", bg='lightblue', fg='black', activebackground="teal", padx=5, pady=5 ).pack(pady= 20)

root.mainloop()  #to bundle pack the code for tkinter


结语

本教程到此为止。希望你已经很好地学习了如何在Python中制作一个随机密码发生器,而且是通过编码一个基于界面的脚本来提高水平。