首頁 > 後端開發 > Python教學 > 建立 Python 密碼產生器:初學者指南

建立 Python 密碼產生器:初學者指南

Linda Hamilton
發布: 2024-10-09 16:19:02
原創
1049 人瀏覽過

託管您的密碼產生器並只為您提供服務是一個了不起的工具,也是一個值得開始的專案;在本指南中,我們將探索如何建立一個簡單的密碼產生器並使用 Pythonanywhere 託管它。

目錄

  1. 密碼安全簡介
  2. 設定您的 Python 環境
  3. 建構密碼產生器
    • 導入必要的模組
    • 建立生成密碼函數
    • 開發主要功能
    • 運行腳本
  4. 理解程式碼
  5. 增強密碼產生器
  6. 在 PythonAnywhere 上託管您的專案
  7. 結論 ## 密碼安全簡介

在資料外洩日益普遍的時代,為每個線上帳戶擁有強大且獨特的密碼比以往任何時候都更加重要。強密碼通常包含大小寫字母、數字和特殊字元的組合。它還應該足夠長以抵抗暴力攻擊。然而,創建和記住此類密碼可能具有挑戰性。這就是密碼產生器派上用場的地方。

設定 Python 環境

在我們深入編碼之前,請確保您的電腦上安裝了 Python。您可以從Python官方網站下載它。對於這個項目,我們將使用 Python 3.12.7

要檢查您的 Python 版本,請開啟命令提示字元或終端機並輸入:

python --version
登入後複製

Build a Python Password Generator: A Beginner

如果您看到以 3 開頭的版本號碼(例如 Python 3.8.5),那麼您就可以開始了。

完整的密碼產生器程式碼

讓我們先查看密碼產生器的完整程式碼。如果它看起來很嚇人,請不要擔心;我們將在下一節中逐行分解它。

import random
import string

def generate_password(length=12):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for _ in range(length))
    return password

def main():
    print("Welcome to the Simple Password Generator!")

    try:
        length = int(input("Enter the desired password length: "))
        if length <= 0:
            raise ValueError("Password length must be positive")
    except ValueError as e:
        print(f"Invalid input: {e}")
        print("Using default length of 12 characters.")
        length = 12

    password = generate_password(length)
    print(f"\nYour generated password is: {password}")

if __name__ == "__main__":
    main()


登入後複製

現在,讓我們分解並詳細檢查每個部分,但在此之前,我們可以看看我寫的這篇精彩文章《使用 Python 構建高級密碼破解器(完整指南)》

Build a Python Password Generator: A Beginner

導入必要的模組

import random
import string
登入後複製

這兩行導入我們的密碼產生器所需的模組:

  • [random](https://www.w3schools.com/python/module_random.asp) 模組提供了產生隨機數和隨機選擇的函數。我們將使用它來隨機選擇密碼字元。

  • [string](https://docs.python.org/3/library/string.html) 模組提供包含各種類型字元(字母、數字、標點符號)的常數。這使我們無需手動輸入密碼中可能需要的所有字元。

    產生密碼函數

def generate_password(length=12):
登入後複製

這一行定義了一個名為generate_password的函式。 Python 中的 def 關鍵字用於定義函數。此函數有一個參數length,預設值為12。這意味著如果在呼叫該函數時沒有指定長度,它將產生一個12個字元的密碼。

characters = string.ascii_letters + string.digits + string.punctuation
登入後複製

此行建立一個名為字元的字串,其中包含我們可能在密碼中使用的所有可能的字元。讓我們來分解一下。

  • string.ascii_letters 包含所有 ASCII 字母,包括小寫 (a-z) 和大寫 (A-Z)。
  • string.digits 包含所有十進制數字 (0-9)。
  • string.punctuation 包含所有標點符號。

透過將這些與運算符相加,我們創建了一個包含所有這些字元的字串。

    password = ''.join(random.choice(characters) for _ in range(length))
登入後複製

這一行是實際密碼產生的地方。這有點複雜,所以讓我們進一步分解它。

  • random.choice(characters) 從我們的字串中隨機選擇一個字元。
  • for _ in range(length) 建立一個運行 length 次的迴圈。底線 _ 用作一次性變數名稱,因為我們不需要使用循環變數。
  • 此循環是生成器表達式的一部分,該表達式會建立隨機選擇的字元的迭代器。
  • ''.join(...) 接受此迭代器並將所有字元連接到一個字串中,每個字元之間有一個空字串 ''。

結果儲存在密碼變數中。

    return password
登入後複製

此行傳回函數產生的密碼。

主要功能

def main():
登入後複製

這一行定義了我們的主函數,它將處理使用者互動並呼叫我們的generate_password函數。

    print("Welcome to the Simple Password Generator!")
登入後複製

此行為使用者列印一則歡迎訊息。

        try:
            length = int(input("Enter the desired password length: "))
            if length <= 0:
                raise ValueError("Password length must be positive")
登入後複製

These lines are part of a try block, which allows us to handle potential errors:

  • We prompt the user to enter a desired password length and attempt to convert their input to an integer using int().
  • If the user enters a value less than or equal to 0, we manually raise a ValueError with a custom message.
        except ValueError as e:
            print(f"Invalid input: {e}")
            print("Using default length of 12 characters.")
            length = 12
登入後複製

This except block catches any ValueError that might occur, either from int() if the user enters a non-numeric value, or from our manually raised error if they enter a non-positive number.

  • We print an error message, including the specific error (e).
  • We inform the user that we'll use the default length of 12 characters.
  • We set length to 12.
        password = generate_password(length)
        print(f"\nYour generated password is: {password}")
登入後複製

These lines call our generate_password function with the specified (or default) length, and then print the resulting password.

Running the Script

    if __name__ == "__main__":
        main()
登入後複製
登入後複製

This block is a common Python idiom. It checks if the script is being run directly (as opposed to being imported as a module). If it is, it calls the main() function.

Lets explore __**name__** = "__main__"

Understanding if __name__ == "__main__" in Python

The line if __name__ == "__main__": might look strange if you're new to Python, but it's a very useful and common pattern. Let's break it down step by step:

Cheeks?

This line checks whether the Python script is being run directly by the user or if it's being imported as a module into another script. Based on this, it decides whether to run certain parts of the code or not.

What are __name__ and "__main__"?

  1. __name__ is a special variable in Python. Python sets this variable automatically for each script that runs.
  2. When you run a Python file directly (like when you type python your_script.py in the command line), Python sets __name__ to the string "__main__" for that script.
  3. However, if your script is imported as a module into another script, __name__ is set to the name of the script/module. ## An analogy to understand this better

Imagine you have a Swiss Army knife. This knife has many tools, like a blade, scissors, and a screwdriver.

  • When you use the knife directly, you use it as the "main" tool. This is like running your Python script directly.
  • But sometimes, you might just want to use one specific tool from the knife as part of a bigger task. This is like importing your script as a module into another script.

The if __name__ == "__main__": check is like the knife asking, "Am I being used as the main tool right now, or am I just lending one of my tools to another task?"

Why is this useful?

This check allows you to write code that can be both run on its own and imported by other scripts without running unintended code. Here's a practical example.

    def greet(name):
        return f"Hello, {name}!"

    def main():
        name = input("Enter your name: ")
        print(greet(name))

    if __name__ == "__main__":
        main()
登入後複製

In this script:

  • If you run it directly, it will ask for your name and greet you.
  • If you import it into another script, you can use the greet function without the script automatically asking for input. ## How it works in our password generator

In our password generator script.

    if __name__ == "__main__":
        main()
登入後複製
登入後複製

This means:

  • If you run the password generator script directly, it will call the main() function and start generating passwords.
  • If you import the script into another Python file, it won't automatically start the password generation process. This allows you to use the generate_password() function in other scripts without running the interactive part. Build a Python Password Generator: A Beginner

Our password generator works, and in the next part of this article, we will modify the password generator to do a lot more, which includes.

Custom Character Sets: Allow users to specify which types of characters they want in their password (e.g., only letters and numbers, no special characters).

Password Strength Checker: Implement a function to evaluate the strength of the generated password and provide feedback to the user.

Multiple Passwords: Give users the option to generate multiple passwords at once.

GUI Interface: Create a graphical user interface using a library like Tkinter to make the program more user-friendly.

Password Storage: Implement a secure way to store generated passwords, possibly with encryption.

資源

  • 密碼破解入門
  • Visual Studio Code 的 20 個基本 Python 擴充
  • 使用 Python 進行網頁抓取與資料擷取
  • Python 入門
  • 使用 Folium 和 Python 建立互動式地圖

以上是建立 Python 密碼產生器:初學者指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板