杰瑞科技汇

Python passwordfield如何实现安全密码输入?

Of course! In Python, a "password field" isn't a single built-in data type like a string or an integer. Instead, it's a concept that involves two key parts:

Python passwordfield如何实现安全密码输入?-图1
(图片来源网络,侵删)
  1. User Input: A secure way to get password input from a user, which typically hides the characters as they are typed (e.g., showing or nothing at all).
  2. Storage: A secure way to store the password in a database or a file, which involves hashing the password, not storing it in plain text.

Let's break down both parts.


Part 1: Securely Getting Password Input from a User

When you need to get a password from a user in a command-line or terminal application, you should use the getpass module. This module is part of Python's standard library, so you don't need to install anything.

The getpass module's getpass() function is the perfect tool. It prompts the user for input but does not echo the characters to the screen.

Example using getpass

import getpass
# Prompt the user for their username
username = input("Username: ")
# Prompt the user for their password securely
password = getpass.getpass("Password: ")
print(f"Hello, {username}.")
# The password is not printed for security reasons.
# We just confirm that input was received.
print("Password received (not shown for security).")

How it looks to the user:

Python passwordfield如何实现安全密码输入?-图2
(图片来源网络,侵删)
Username: alice
Password:  <-- As you type, nothing appears on the screen.
Hello, alice.
Password received (not shown for security).

This is the standard and most secure way to handle password input in a command-line script.


Part 2: Securely Storing and Verifying Passwords

This is the most critical part. You should never store passwords as plain text. If your database is ever compromised, all user passwords will be exposed.

The correct practice is to:

  1. Hash the password using a strong, salted, one-way cryptographic hash function.
  2. Store the hash (and the salt) in your database.
  3. When a user tries to log in, you hash the password they provide and compare it to the stored hash.

What is Hashing?

A hash function takes an input (like a password) and produces a fixed-size, unique string of characters (the hash). Key properties:

Python passwordfield如何实现安全密码输入?-图3
(图片来源网络,侵删)
  • One-way: You cannot easily reverse the hash to get the original password.
  • Deterministic: The same input will always produce the same hash.
  • Fast to compute, slow to "crack": Good algorithms are designed to be slow, making brute-force attacks difficult.

What is Salting?

A salt is a random piece of data that is unique to each user. You add it to the password before hashing. This prevents attackers from using pre-computed lists of hashes (called "rainbow tables") to crack passwords.

Recommended Library: bcrypt

For handling password hashing, the bcrypt library is the industry standard. It's designed to be slow (which is good for security) and handles salting automatically.

First, you need to install it:

pip install bcrypt

Example: Hashing a Password

import bcrypt
# The password the user provides (in bytes)
# The 'encode()' is important because bcrypt works with bytes, not strings.
password = "my_super_secret_password".encode('utf-8')
# Generate a salt and hash the password
# gensalt() generates a random salt for you
hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())
print(f"Original Password: {password.decode('utf-8')}")
print(f"Hashed Password:   {hashed_password.decode('utf-8')}")
# --- In a real application, you would store this hashed_password in your database.
# For example:
# user_db = {
#     "alice": b'$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LeZeUfkZMBs9kYZmW' # Example hash
# }

Example: Verifying a Password

When a user logs in, you retrieve the stored hash from the database and compare it to the hash of the password they just entered.

import bcrypt
# This is the hash you would retrieve from your database for the user
stored_hashed_password = b'$2b$12$LQv1c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LeZeUfkZMBs9kYZmW' # Example hash
# The password the user is trying to log in with
login_attempt = "my_super_secret_password".encode('utf-8')
# Check if the login attempt matches the stored hash
if bcrypt.checkpw(login_attempt, stored_hashed_password):
    print("Login successful! Welcome back.")
else:
    print("Login failed! Incorrect password.")
# --- Example of a failed login ---
failed_attempt = "this_is_the_wrong_password".encode('utf-8')
if bcrypt.checkpw(failed_attempt, stored_hashed_password):
    print("Login successful! Welcome back.")
else:
    print("Login failed! Incorrect password.")

Complete Example: A Simple Command-Line Login System

Here's how you can combine getpass for input and bcrypt for storage and verification into a simple, practical example.

import getpass
import bcrypt
import json
import os
# In a real app, this would be a database file or a proper database.
USER_DB_FILE = "users.json"
def load_users():
    """Loads user data from a JSON file."""
    if not os.path.exists(USER_DB_FILE):
        return {}
    with open(USER_DB_FILE, 'r') as f:
        return json.load(f)
def save_users(users):
    """Saves user data to a JSON file."""
    with open(USER_DB_FILE, 'w') as f:
        json.dump(users, f, indent=4)
def register_user():
    """Registers a new user."""
    print("\n--- Register ---")
    username = input("Choose a username: ")
    # Check if user already exists
    users = load_users()
    if username in users:
        print("Username already exists. Please choose another.")
        return
    # Get and hash the password
    password = getpass.getpass("Choose a password: ")
    hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
    # Save the new user
    users[username] = hashed_password
    save_users(users)
    print(f"User '{username}' registered successfully!")
def login_user():
    """Logs an existing user in."""
    print("\n--- Login ---")
    username = input("Username: ")
    password = getpass.getpass("Password: ")
    users = load_users()
    stored_hash = users.get(username)
    if stored_hash and bcrypt.checkpw(password.encode('utf-8'), stored_hash.encode('utf-8')):
        print(f"\nLogin successful! Welcome, {username}.")
    else:
        print("\nLogin failed! Invalid username or password.")
def main():
    """Main function to run the CLI application."""
    while True:
        print("\n1. Register")
        print("2. Login")
        print("3. Exit")
        choice = input("Choose an option: ")
        if choice == '1':
            register_user()
        elif choice == '2':
            login_user()
        elif choice == '3':
            print("Goodbye!")
            break
        else:
            print("Invalid choice. Please try again.")
if __name__ == "__main__":
    main()

Summary

Task Python Tool/Library Why?
Get Input getpass module Securely hides password characters from the screen as the user types.
Hash & Store bcrypt library Industry-standard for password hashing. Automatically handles secure salting and is slow to crack.
Store Data json module A simple way to persist user data (hashes) between script runs. For production, use a real database.
分享:
扫描分享到社交APP
上一篇
下一篇