UF6

secert_password_generator

UF6
Dec 22nd, 2025
3,732
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.19 KB | Cybersecurity | 0 0
  1. import secrets
  2. import string
  3. import argparse
  4. import sys
  5.  
  6. def generate_secure_password(length=16):
  7.     """
  8.    Generates a cryptographically secure random password.
  9.    Ensures at least one lowercase, one uppercase, one digit, and one special character.
  10.    """
  11.     # Define the character sets
  12.     letters_low = string.ascii_lowercase
  13.     letters_up = string.ascii_uppercase
  14.     digits = string.digits
  15.     symbols = string.punctuation
  16.    
  17.     # Combine all characters for the main pool
  18.     all_characters = letters_low + letters_up + digits + symbols
  19.  
  20.     while True:
  21.         # Generate a password using secrets.choice for cryptographic security
  22.         password = ''.join(secrets.choice(all_characters) for _ in range(length))
  23.        
  24.         # Security Check: Ensure the password meets 'strength' criteria
  25.         # This prevents the 'random' chance of getting a password with only numbers
  26.         if (any(c in letters_low for c in password)
  27.                 and any(c in letters_up for c in password)
  28.                 and any(c in digits for c in password)
  29.                 and any(c in symbols for c in password)):
  30.             return password
  31.  
  32. def main():
  33.     # Setup command line arguments (from your first script)
  34.     parser = argparse.ArgumentParser(description='Generate a cryptographically secure password.')
  35.     parser.add_argument('length', type=int, nargs='?', help='Length of the password')
  36.     args = parser.parse_args()
  37.  
  38.     # Determine length: use argument, or ask user if no argument was provided
  39.     if args.length:
  40.         length = args.length
  41.     else:
  42.         try:
  43.             user_input = input("Enter password length (default 16): ")
  44.             length = int(user_input) if user_input.strip() else 16
  45.         except ValueError:
  46.             print("Invalid input. Using default length of 16.")
  47.             length = 16
  48.  
  49.     if length < 4:
  50.         print("Error: Length must be at least 4 to satisfy complexity requirements.")
  51.         sys.exit(1)
  52.  
  53.     # Generate and print
  54.     secure_password = generate_secure_password(length)
  55.     print("-" * 30)
  56.     print(f"Generated Secure Password: {secure_password}")
  57.     print("-" * 30)
  58.  
  59. if __name__ == '__main__':
  60.     main()
Advertisement
Add Comment
Please, Sign In to add comment