Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import secrets
- import string
- import argparse
- import sys
- def generate_secure_password(length=16):
- """
- Generates a cryptographically secure random password.
- Ensures at least one lowercase, one uppercase, one digit, and one special character.
- """
- # Define the character sets
- letters_low = string.ascii_lowercase
- letters_up = string.ascii_uppercase
- digits = string.digits
- symbols = string.punctuation
- # Combine all characters for the main pool
- all_characters = letters_low + letters_up + digits + symbols
- while True:
- # Generate a password using secrets.choice for cryptographic security
- password = ''.join(secrets.choice(all_characters) for _ in range(length))
- # Security Check: Ensure the password meets 'strength' criteria
- # This prevents the 'random' chance of getting a password with only numbers
- if (any(c in letters_low for c in password)
- and any(c in letters_up for c in password)
- and any(c in digits for c in password)
- and any(c in symbols for c in password)):
- return password
- def main():
- # Setup command line arguments (from your first script)
- parser = argparse.ArgumentParser(description='Generate a cryptographically secure password.')
- parser.add_argument('length', type=int, nargs='?', help='Length of the password')
- args = parser.parse_args()
- # Determine length: use argument, or ask user if no argument was provided
- if args.length:
- length = args.length
- else:
- try:
- user_input = input("Enter password length (default 16): ")
- length = int(user_input) if user_input.strip() else 16
- except ValueError:
- print("Invalid input. Using default length of 16.")
- length = 16
- if length < 4:
- print("Error: Length must be at least 4 to satisfy complexity requirements.")
- sys.exit(1)
- # Generate and print
- secure_password = generate_secure_password(length)
- print("-" * 30)
- print(f"Generated Secure Password: {secure_password}")
- print("-" * 30)
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment