Random Password Generator with Special Characters

  • Share this:

Code introduction


This function generates a random password of a specified length, with an option to include special characters.


Technology Stack : random, string

Code Type : Generate random password

Code Difficulty : Intermediate


                
                    
import random
import math
import datetime
import hashlib
import re
import os
import shutil
import subprocess
import sys
import getpass
import json

def generate_random_password(length, use_special_chars=True):
    """
    Generate a random password with a specified length and optional special characters.
    """
    if length < 8:
        raise ValueError("Password length must be at least 8 characters.")
    
    chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    if use_special_chars:
        chars += '!@#$%^&*()_+-=[]{}|;:,.<>?'
    
    password = ''.join(random.choice(chars) for i in range(length))
    return password                
              
Tags: