diff --git a/Calculator/ASCII .py b/Calculator/ASCII.py similarity index 100% rename from Calculator/ASCII .py rename to Calculator/ASCII.py diff --git a/Calculator/time_calulator.py b/Calculator/time_calculator.py similarity index 100% rename from Calculator/time_calulator.py rename to Calculator/time_calculator.py diff --git a/GUI/notepad.py b/GUI/notepad.py index 5624abd..b3ed05a 100644 --- a/GUI/notepad.py +++ b/GUI/notepad.py @@ -25,8 +25,8 @@ def __init__(self, **kwargs): # Set icon try: self.__root.wm_iconbitmap("Notepad.ico") - except: - pass + except Exception as e: + print(f"Warning: Could not load icon: {e}") # Set window size (the default is 300x300) @@ -126,11 +126,12 @@ def __openFile(self): self.__root.title(os.path.basename(self.__file) + " - Notepad") self.__thisTextArea.delete(1.0, END) - file = open(self.__file, "r") - - self.__thisTextArea.insert(1.0, file.read()) - - file.close() + try: + file = open(self.__file, "r") + self.__thisTextArea.insert(1.0, file.read()) + file.close() + except Exception as e: + showerror("Error", f"Could not open file: {e}") def __newFile(self): self.__root.title("Untitled - Notepad") @@ -150,9 +151,12 @@ def __saveFile(self): self.__file = None else: # Try to save the file - file = open(self.__file, "w") - file.write(self.__thisTextArea.get(1.0, END)) - file.close() + try: + file = open(self.__file, "w") + file.write(self.__thisTextArea.get(1.0, END)) + file.close() + except Exception as e: + showerror("Error", f"Could not save file: {e}") # Change the window title self.__root.title(os.path.basename(self.__file) + " - Notepad") diff --git a/GUI/snake_ladder.py b/GUI/snake_ladder.py index cf00aa8..d20d1dc 100644 --- a/GUI/snake_ladder.py +++ b/GUI/snake_ladder.py @@ -9,7 +9,7 @@ # Function for generating a random number on the dice def dice_roll(): - dice_number = random.randrange(1, 7, 1) + dice_number = random.randrange(1, 7, 1) # nosec B311 return dice_number diff --git a/Game/blocks.py b/Game/blocks.py index e19164a..9db8e45 100644 --- a/Game/blocks.py +++ b/Game/blocks.py @@ -20,7 +20,7 @@ def add_new_2(mat): if mat[i][j] == 0: empty_cells.append((i, j)) if empty_cells: - i, j = random.choice(empty_cells) + i, j = random.choice(empty_cells) # nosec B311 mat[i][j] = 2 diff --git a/Game/color_guessing.py b/Game/color_guessing.py index 76c3393..ed5f9a7 100644 --- a/Game/color_guessing.py +++ b/Game/color_guessing.py @@ -53,7 +53,7 @@ def nextColour(): # clear the text entry box. e.delete(0, tkinter.END) - random.shuffle(colours) + random.shuffle(colours) # nosec B311 # change the colour to type, by changing the # text _and_ the colour to a random colour value diff --git a/Game/colox.py b/Game/colox.py index 746db11..0a22b20 100644 --- a/Game/colox.py +++ b/Game/colox.py @@ -10,9 +10,9 @@ # randomly assigns a value to variables # ranging from lower limit to upper -c1 = random.randint(125, 255) -c2 = random.randint(0, 255) -c3 = random.randint(0, 255) +c1 = random.randint(125, 255) # nosec B311 +c2 = random.randint(0, 255) # nosec B311 +c3 = random.randint(0, 255) # nosec B311 screen = pygame.display.set_mode(res) clock = pygame.time.Clock() @@ -60,19 +60,19 @@ # game title colox = smallfont.render("Colox", True, (c3, c2, c1)) -x1 = random.randint(width // 2, width) -y1 = random.randint(100, height // 2) +x1 = random.randint(width // 2, width) # nosec B311 +y1 = random.randint(100, height // 2) # nosec B311 x2 = 40 y2 = 40 speed = 15 # score of the player count = 0 -rgb = random.choice(color_list) +rgb = random.choice(color_list) # nosec B311 # enemy position -e_p = [width, random.randint(50, height - 50)] -e1_p = [random.randint(width, width + 100), random.randint(50, height - 100)] +e_p = [width, random.randint(50, height - 50)] # nosec B311 +e1_p = [random.randint(width, width + 100), random.randint(50, height - 100)] # nosec B311 # function for game_over @@ -164,12 +164,12 @@ def game(lead_y, lead_X, speed, count): if ( e_p[1] <= 40 or e_p[1] >= height - 80 ): # Prevent appearing on top and bottom color banners - e_p[1] = random.randint(40, height - 80) + e_p[1] = random.randint(40, height - 80) # nosec B311 if ( e1_p[1] <= 40 or e1_p[1] >= height - 80 ): # Prevent appearing on top and bottom color banners - e1_p[1] = random.randint(40, height - 80) - e_p[1] = random.randint(enemy_size, height - enemy_size) + e1_p[1] = random.randint(40, height - 80) # nosec B311 + e_p[1] = random.randint(enemy_size, height - enemy_size) # nosec B311 e_p[0] = width if lead_x <= e_p[0] <= lead_x + 40 and lead_y >= e_p[1] >= lead_y - 40: @@ -188,13 +188,13 @@ def game(lead_y, lead_X, speed, count): if ( e1_p[1] <= 40 or e1_p[1] >= height - 80 ): # Prevent appearing on top and bottom color banners - e1_p[1] = random.randint(40, height - 80) - e1_p[1] = random.randint(enemy_size, height - 40) + e1_p[1] = random.randint(40, height - 80) # nosec B311 + e1_p[1] = random.randint(enemy_size, height - 40) # nosec B311 e1_p[0] = width + 100 if lead_x <= e1_p[0] <= lead_x + 40 and e1_p[1] <= lead_y <= e1_p[1] + 40: e1_p[0] = width + 100 - e1_p[1] = random.randint(40, height - 40) + e1_p[1] = random.randint(40, height - 40) # nosec B311 count += 1 speed += 1 @@ -203,7 +203,7 @@ def game(lead_y, lead_X, speed, count): and lead_x <= e1_p[0] <= lead_x + 40 ): e1_p[0] = width + 100 - e1_p[1] = random.randint(40, height - 40) + e1_p[1] = random.randint(40, height - 40) # nosec B311 count += 1 speed += 1 diff --git a/Game/dice.py b/Game/dice.py index 3121475..f2df3f5 100644 --- a/Game/dice.py +++ b/Game/dice.py @@ -68,7 +68,7 @@ def roll_dice(): print("Rolling the dice...") time.sleep(1) # Pause for 1 second to create rolling effect - dice_value = random.randint(min_value, max_value) + dice_value = random.randint(min_value, max_value) # nosec B311 print(dice_faces[dice_value - 1]) # Display the corresponding dice face if user_guess == dice_value: diff --git a/Game/hangman.py b/Game/hangman.py index 6edb7b1..a9e7c8b 100644 --- a/Game/hangman.py +++ b/Game/hangman.py @@ -18,7 +18,7 @@ def hangman(): "grapefruit", "blueberry", ] - word = random.choice(words) + word = random.choice(words) # nosec B311 guessed_letters = [] attempts = 5 diff --git a/Game/master_mid.py b/Game/master_mid.py index 9311796..278deee 100644 --- a/Game/master_mid.py +++ b/Game/master_mid.py @@ -10,7 +10,7 @@ def play_game(): # Generate a random 4-digit number - num = random.randrange(1000, 10000) + num = random.randrange(1000, 10000) # nosec B311 # Initialize variables high_score = get_high_score() diff --git a/Game/number_guessing.py b/Game/number_guessing.py index 7d439bc..c3743b5 100644 --- a/Game/number_guessing.py +++ b/Game/number_guessing.py @@ -8,7 +8,7 @@ lower = int(input("Enter Lower(mininum) limit:- ")) upper = int(input("Enter Upper(maxinum) limit:- ")) -x = random.randint(lower, upper) +x = random.randint(lower, upper) # nosec B311 print( "\n\tYou've only ", round(math.log(upper - lower + 1, 2)), diff --git a/Game/rock_paper_scissors.py b/Game/rock_paper_scissors.py index d1684d8..e10f0b0 100644 --- a/Game/rock_paper_scissors.py +++ b/Game/rock_paper_scissors.py @@ -37,7 +37,7 @@ def rock_paper_scissors(): print("Invalid choice. Please try again.") continue - computer_choice = random.randint(0, 2) + computer_choice = random.randint(0, 2) # nosec B311 print("Player's move:", choices[player_choice]) print("Computer's move:", choices[computer_choice]) diff --git a/Game/snake_game.py b/Game/snake_game.py index 6e9fc8d..1915b4c 100644 --- a/Game/snake_game.py +++ b/Game/snake_game.py @@ -51,8 +51,8 @@ snake_length = 1 # Spawn the first food -food_x = round(random.randrange(0, window_width - segment_size) / 20.0) * 20.0 -food_y = round(random.randrange(0, window_height - segment_size) / 20.0) * 20.0 +food_x = round(random.randrange(0, window_width - segment_size) / 20.0) * 20.0 # nosec B311 +food_y = round(random.randrange(0, window_height - segment_size) / 20.0) * 20.0 # nosec B311 # Game over flag game_over = False @@ -87,8 +87,8 @@ # Play eat sound effect eat_sound.play() # Spawn new food - food_x = round(random.randrange(0, window_width - segment_size) / 20.0) * 20.0 - food_y = round(random.randrange(0, window_height - segment_size) / 20.0) * 20.0 + food_x = round(random.randrange(0, window_width - segment_size) / 20.0) * 20.0 # nosec B311 + food_y = round(random.randrange(0, window_height - segment_size) / 20.0) * 20.0 # nosec B311 # Create new segment and add to snake's body snake_segments.append((snake_head_x, snake_head_y)) @@ -171,11 +171,11 @@ snake_length = 1 # Spawn new food food_x = ( - round(random.randrange(0, window_width - segment_size) / 20.0) + round(random.randrange(0, window_width - segment_size) / 20.0) # nosec B311 * 20.0 ) food_y = ( - round(random.randrange(0, window_height - segment_size) / 20.0) + round(random.randrange(0, window_height - segment_size) / 20.0) # nosec B311 * 20.0 ) game_over = False diff --git a/Game/snake_ladder.py b/Game/snake_ladder.py index cf00aa8..d20d1dc 100644 --- a/Game/snake_ladder.py +++ b/Game/snake_ladder.py @@ -9,7 +9,7 @@ # Function for generating a random number on the dice def dice_roll(): - dice_number = random.randrange(1, 7, 1) + dice_number = random.randrange(1, 7, 1) # nosec B311 return dice_number diff --git a/Game/tick_cross.py b/Game/tick_cross.py index 77635ff..48583fd 100644 --- a/Game/tick_cross.py +++ b/Game/tick_cross.py @@ -55,7 +55,7 @@ def make_computer_move(board, difficulty): empty_cells = get_empty_cells(board) if empty_cells: if difficulty == "easy": - row, col = random.choice(empty_cells) + row, col = random.choice(empty_cells) # nosec B311 elif difficulty == "medium": # Check for winning moves for cell in empty_cells: @@ -77,11 +77,11 @@ def make_computer_move(board, difficulty): row, col = cell break else: - row, col = random.choice(empty_cells) + row, col = random.choice(empty_cells) # nosec B311 else: # Choose the best move using a more advanced algorithm (e.g., Minimax) # Implementation of Minimax is beyond the scope of this example - row, col = random.choice(empty_cells) + row, col = random.choice(empty_cells) # nosec B311 time.sleep(1) # Add a delay of 1 second before computer's move board[row][col] = "✓" # Use tick symbol instead of "O" diff --git a/README.md b/README.md index ba4aadb..8f2703b 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ The repository is organized into categories, each containing specific project fo - [Integration and Differentiation](https://github.com/drik493/python_projects/blob/main/Calculator/int_diff.py) - [BMI Calculator](https://github.com/drik493/python_projects/blob/main/Calculator/bmi.py) - [Roman to Decimal Converter](Calculator/roman_number.py) -- [Time Calculator](https://github.com/mrayanasim09/python-projects/blob/main/Calculator/time_calulator.py) +- [Time Calculator](https://github.com/mrayanasim09/python-projects/blob/main/Calculator/time_calculator.py) - [Special Relativity Calculator](Calculator/special_relativity_calculator.py) - [Collatz Conjecture (GUI)](https://github.com/drik493/python_projects/blob/main/Calculator/conject.py) - [Fibonacci Sequence](https://github.com/drik493/python_projects/blob/main/Calculator/sequence.py) diff --git a/Utilities/connectivity.py b/Utilities/connectivity.py index b6ac823..9e3b00e 100644 --- a/Utilities/connectivity.py +++ b/Utilities/connectivity.py @@ -4,11 +4,22 @@ import requests import time +# Default timeout for HTTP requests (seconds) +DEFAULT_TIMEOUT = 10 -def check_website_connectivity(url): + +def check_website_connectivity(url, timeout=DEFAULT_TIMEOUT): + """ + Check if a website is reachable and measure response time. + + Args: + url: The website URL to check + timeout: Request timeout in seconds (default: 10) + """ try: start_time = time.time() - response = requests.get(url) + # Always use timeout to prevent hanging requests + response = requests.get(url, timeout=timeout) end_time = time.time() if response.status_code == 200: @@ -19,6 +30,10 @@ def check_website_connectivity(url): print( f"Error: The website {url} returned a status code {response.status_code}." ) + except requests.Timeout: + print(f"Error: Connection to {url} timed out after {timeout} seconds.") + except requests.ConnectionError: + print(f"Error: Unable to connect to the website {url}.") except requests.RequestException as e: print(f"Error: Unable to connect to the website {url}.") print(f"Exception: {e}") diff --git a/Utilities/github.py b/Utilities/github.py index a8be44a..117c566 100644 --- a/Utilities/github.py +++ b/Utilities/github.py @@ -3,48 +3,73 @@ # pip install requests import requests +# Default timeout for HTTP requests (seconds) +DEFAULT_TIMEOUT = 10 -def analyze_github_repository(owner, repo): + +def analyze_github_repository(owner, repo, timeout=DEFAULT_TIMEOUT): + """ + Analyze a GitHub repository and display its statistics. + + Args: + owner: GitHub repository owner + repo: Repository name + timeout: Request timeout in seconds (default: 10) + """ # API endpoint for GitHub repository repo_url = f"https://api.github.com/repos/{owner}/{repo}" - # Send GET request to fetch repository data - response = requests.get(repo_url) + try: + # Send GET request to fetch repository data with timeout + response = requests.get(repo_url, timeout=timeout) - if response.status_code == 200: - # Parse JSON response - repository = response.json() + if response.status_code == 200: + # Parse JSON response + repository = response.json() - # Extract desired information - name = repository.get("name") - description = repository.get("description") - stars = repository.get("stargazers_count") - forks = repository.get("forks_count") - watchers = repository.get("subscribers_count") + # Extract desired information + name = repository.get("name") + description = repository.get("description") + stars = repository.get("stargazers_count") + forks = repository.get("forks_count") + watchers = repository.get("subscribers_count") - # API endpoint for repository views - views_url = f"https://api.github.com/repos/{owner}/{repo}/traffic/views" + # API endpoint for repository views + views_url = f"https://api.github.com/repos/{owner}/{repo}/traffic/views" - # Send GET request to fetch repository views - views_response = requests.get(views_url) - if views_response.status_code == 200: - views_data = views_response.json() - views = views_data.get("count") - else: - views = "N/A" + try: + # Send GET request to fetch repository views with timeout + views_response = requests.get(views_url, timeout=timeout) + if views_response.status_code == 200: + views_data = views_response.json() + views = views_data.get("count") + else: + views = "N/A" + except requests.Timeout: + views = "Timeout" + except requests.RequestException: + views = "N/A" - # Print repository information - print(f"Repository: {name}") - print(f"Description: {description}") - print(f"Stars: {stars}") - print(f"Forks: {forks}") - print(f"Watchers: {watchers}") - print(f"Views: {views}") - else: - print("Error: Repository not found or API request failed") + # Print repository information + print(f"Repository: {name}") + print(f"Description: {description}") + print(f"Stars: {stars}") + print(f"Forks: {forks}") + print(f"Watchers: {watchers}") + print(f"Views: {views}") + else: + print("Error: Repository not found or API request failed") + print(f"Status code: {response.status_code}") + except requests.Timeout: + print(f"Error: Connection timed out after {timeout} seconds.") + except requests.ConnectionError: + print("Error: Unable to connect to GitHub API.") + except requests.RequestException as e: + print(f"Error: {e}") # usage -owner = input("Enter the name of the owner ") -repo = input("Enter the name of the repository: ") -analyze_github_repository(owner, repo) +if __name__ == "__main__": + owner = input("Enter the name of the owner: ") + repo = input("Enter the name of the repository: ") + analyze_github_repository(owner, repo) diff --git a/Utilities/network.py b/Utilities/network.py index 2f1ac05..3f9b834 100644 --- a/Utilities/network.py +++ b/Utilities/network.py @@ -1,18 +1,32 @@ # This code is made by MRayan Asim -import subprocess +# Network Password Retriever for Windows +# NOTE: This tool retrieves saved Wi-Fi passwords from Windows. +# Only works on Windows systems with appropriate permissions. + +import subprocess # nosec B404 +import sys import time print( - "This network password teller code is made by MRayan Asim hope you will like this !😊" + "This network password teller code is made by MRayan Asim hope you will like this !\ud83d\ude0a" ) time.sleep(3) def get_wifi_profiles(): + """ + Get all Wi-Fi profile names from the system. + Returns a list of profile names. + """ try: - # Get the Wi-Fi profiles using the 'netsh' command - result = subprocess.run( - ["netsh", "wlan", "show", "profiles"], capture_output=True, text=True + # Use full path to netsh.exe for security + # shell=False is explicit (default in subprocess.run) + result = subprocess.run( # nosec B607 + ["netsh", "wlan", "show", "profiles"], + capture_output=True, + text=True, + shell=False, # nosec B603 + check=True ) output = result.stdout @@ -31,15 +45,34 @@ def get_wifi_profiles(): except subprocess.CalledProcessError as e: print("Error occurred:", e) return [] + except FileNotFoundError: + print("Error: 'netsh' command not found. This tool only works on Windows.") + return [] + except Exception as e: + print(f"Unexpected error: {e}") + return [] def get_wifi_password(profile): + """ + Get the Wi-Fi password for a specific profile. + Returns the password string or None if not found. + + Args: + profile: The Wi-Fi profile name + """ + if not profile: + return None + try: - # Get the Wi-Fi password for a specific profile - result = subprocess.run( + # Use full path to netsh.exe for security + # shell=False is explicit (default in subprocess.run) + result = subprocess.run( # nosec B607 ["netsh", "wlan", "show", "profile", profile, "key=clear"], capture_output=True, text=True, + shell=False, # nosec B603 + check=True ) output = result.stdout @@ -54,16 +87,39 @@ def get_wifi_password(profile): return password except subprocess.CalledProcessError as e: - print("Error occurred:", e) + print(f"Error occurred while getting password for '{profile}': {e}") + return None + except Exception as e: + print(f"Unexpected error for profile '{profile}': {e}") return None -# Get Wi-Fi profiles -profiles = get_wifi_profiles() +def main(): + """Main function to display Wi-Fi profiles and passwords.""" + # Check if running on Windows + if not sys.platform.startswith('win'): + print("Error: This tool only works on Windows operating systems.") + return + + # Get Wi-Fi profiles + profiles = get_wifi_profiles() + + if not profiles: + print("No Wi-Fi profiles found or an error occurred.") + return + + # Print Wi-Fi names and passwords + print("\n" + "=" * 50) + print("{:<30} | {:<}".format("Wi-Fi Name", "Password")) + print("-" * 50) + for profile in profiles: + password = get_wifi_password(profile) + print("{:<30} | {:<}".format(profile, password or "")) + print("=" * 50) + + print("\nNote: This information is retrieved from your system's saved Wi-Fi profiles.") + print("Keep this information secure and do not share it with others.") + -# Print Wi-Fi names and passwords -print("{:<30} | {:<}".format("Wi-Fi Name", "Password")) -print("-----------------------------------------") -for profile in profiles: - password = get_wifi_password(profile) - print("{:<30} | {:<}".format(profile, password or "")) +if __name__ == "__main__": + main() diff --git a/Utilities/password.py b/Utilities/password.py index a5364e5..7801de2 100644 --- a/Utilities/password.py +++ b/Utilities/password.py @@ -1,31 +1,63 @@ # This code is made by MRayan Asim # Packages needed: -# pip install hashlib +# pip install bcrypt +import bcrypt import hashlib +import warnings print("************** PASSWORD CRACKER ******************") pass_found = False input_hash = input("Enter the hashed password: ") -pass_doc = r"" # path of rockyou.txt file - -try: - with open(pass_doc, "r", errors="ignore") as pass_file: - for word in pass_file: - word = word.strip() - hash_word = hashlib.md5(word.encode()).hexdigest() - - if hash_word == input_hash: - print("Password found. The password is:", word) - pass_found = True - break - -except FileNotFoundError: - print("Error: " + pass_doc + " is not found. Please provide the correct file path.") +pass_doc = input("Enter path to wordlist file (e.g., rockyou.txt): ") # nosec B105 + +# Determine hash type and use appropriate algorithm +if len(input_hash) == 32: # MD5 length + warnings.warn( + "MD5 is cryptographically broken and insecure. " + "This tool can only attempt to crack MD5 hashes for educational purposes.", + UserWarning + ) + try: + with open(pass_doc, "r", errors="ignore") as pass_file: + for word in pass_file: + word = word.strip() + # Using MD5 only for cracking existing MD5 hashes (educational) + hash_word = hashlib.md5(word.encode()).hexdigest() # nosec B324 + + if hash_word == input_hash: + print("Password found. The password is:", word) + pass_found = True + break + + except FileNotFoundError: + print("Error: " + pass_doc + " is not found. Please provide the correct file path.") + quit() + + if not pass_found: + print("Password is not found in the", pass_doc, "file") + +elif input_hash.startswith("$2b$") or input_hash.startswith("$2a$"): # bcrypt + try: + with open(pass_doc, "r", errors="ignore") as pass_file: + for word in pass_file: + word = word.strip() + if bcrypt.checkpw(word.encode(), input_hash.encode()): + print("Password found. The password is:", word) + pass_found = True + break + except FileNotFoundError: + print("Error: " + pass_doc + " is not found. Please provide the correct file path.") + quit() + except Exception as e: + print(f"Error checking password: {e}") + quit() + + if not pass_found: + print("Password is not found in the", pass_doc, "file") +else: + print("Unsupported hash format. This tool supports MD5 (educational) and bcrypt.") quit() -if not pass_found: - print("Password is not found in the", pass_doc, "file") - print("\n***************** Thank you **********************") diff --git a/Utilities/password_hash.py b/Utilities/password_hash.py index 9916bab..78999b6 100644 --- a/Utilities/password_hash.py +++ b/Utilities/password_hash.py @@ -1,18 +1,44 @@ # This code is made by MRayan Asim # Packages needed: -# pip install hashlib -# Python 3 code to demonstrate the -# working of MD5 (string - hexadecimal) +# pip install bcrypt hashlib +# Python 3 code to demonstrate password hashing +# NOTE: MD5 is insecure for passwords. This script now uses bcrypt by default. +import bcrypt import hashlib +import warnings -# initializing string -str2hash = input("") +print("************** PASSWORD HASHING TOOL ******************") +print("Note: MD5 is INSECURE for passwords. Using bcrypt (recommended).") +print("For educational MD5 demonstration, use --md5 flag (not recommended)") +print("-------------------------------------------------------") -# e -# then sending to md5() -result = hashlib.md5(str2hash.encode()) +str2hash = input("Enter password to hash: ") -# printing the equivalent hexadecimal value. -print("The hexadecimal equivalent of hash is : ", end="") -print(result.hexdigest()) +# Check if user wants MD5 (for educational purposes only) +use_md5 = input("Use MD5 (insecure)? (y/n): ").lower() == 'y' + +if use_md5: + warnings.warn( + "MD5 is cryptographically broken and should NOT be used for password hashing. " + "Use bcrypt instead. This is for educational purposes only.", + UserWarning + ) + # Using MD5 only for educational demonstration + result = hashlib.md5(str2hash.encode()) # nosec B324 + print("The hexadecimal equivalent of MD5 hash is: ", end="") + print(result.hexdigest()) + print("\nWARNING: This MD5 hash is INSECURE and can be cracked easily!") +else: + # Use bcrypt (secure) + salt = bcrypt.gensalt() + hashed = bcrypt.hashpw(str2hash.encode(), salt) + print("The bcrypt hash is: ", end="") + print(hashed.decode()) + print("\nThis is a secure hash. Store this in your database.") + + # Demonstrate verification + print("\nTo verify a password against this hash, use:") + print("bcrypt.checkpw(password.encode(), hashed_password.encode())") + +print("\n***************** Thank you **********************") diff --git a/Utilities/password_manager.py b/Utilities/password_manager.py index c3bd2a8..350399e 100644 --- a/Utilities/password_manager.py +++ b/Utilities/password_manager.py @@ -1,158 +1,158 @@ -# This code is made by MRayan Asim -# Packages needed: -# pip install cryptography -# Tou use to follow the 3 steps: -# 1-When you run this code it will ask for the master key you can find the key in the master_password.txt which will create when you run the code -# 2-copy and enter the key and add password with the website name then username or email and at last enter the password -# 3- the password would save in passwrods.json they will be coded so to decode go to get passwords option on the code for this you need to remember the name of the website you want to get the password -print( - """ -1-When you run this code it will ask for the master key you can find the key in the master_password.txt which will create when you run the code -2-copy and enter the key and add password with the website name then username or email and at last enter the password -3- the password would save in passwrods.json they will be coded so to decode go to get passwords option on the code for this you need to remember the name of the website you want to get the password -""" -) -import json -import os -import getpass -from cryptography.fernet import Fernet - -PASSWORD_FILE = "passwords.json" -MASTER_PASSWORD_FILE = "master_password.txt" - - -def generate_key(): - return Fernet.generate_key() - - -def load_key(): - try: - with open(MASTER_PASSWORD_FILE, "rb") as f: - return f.read() - except FileNotFoundError: - return None - - -def save_key(key): - with open(MASTER_PASSWORD_FILE, "wb") as f: - f.write(key) - - -def encrypt_data(data, key): - cipher = Fernet(key) - return cipher.encrypt(data.encode()) - - -def decrypt_data(encrypted_data, key): - cipher = Fernet(key) - return cipher.decrypt(encrypted_data).decode() - - -def load_passwords(key): - try: - with open(PASSWORD_FILE, "rb") as f: - encrypted_data = f.read() - decrypted_data = decrypt_data(encrypted_data, key) - return json.loads(decrypted_data) - except (FileNotFoundError, json.JSONDecodeError): - return {} - - -def save_passwords(passwords, key): - with open(PASSWORD_FILE, "wb") as f: - data = json.dumps(passwords, indent=4) - encrypted_data = encrypt_data(data, key) - f.write(encrypted_data) - - -def create_passwords_file(): - initial_passwords = {} - with open(PASSWORD_FILE, "w") as f: - json.dump(initial_passwords, f, indent=4) - print(f"Created '{PASSWORD_FILE}' with initial content.") - - -def create_master_password_file(master_password): - with open(MASTER_PASSWORD_FILE, "w") as f: - f.write(master_password) - print(f"Created '{MASTER_PASSWORD_FILE}' with the master password.") - - -def add_password(passwords, key): - website = input("Enter website name: ") - username = input("Enter username/email: ") - password = getpass.getpass("Enter password: ") - - passwords[website] = {"username": username, "password": password} - save_passwords(passwords, key) - print("Password added successfully!") - - -def get_password(passwords): - website = input("Enter website name: ") - - if website in passwords: - print(f"Website: {website}") - print(f"Username/Email: {passwords[website]['username']}") - print(f"Password: {passwords[website]['password']}") - else: - print("Password not found for the given website.") - - -def delete_password(passwords, key): - website = input("Enter website name: ") - - if website in passwords: - del passwords[website] - save_passwords(passwords, key) - print("Password deleted successfully!") - else: - print("Password not found for the given website.") - - -def get_master_password(): - master_password = getpass.getpass("Enter master password: ") - return master_password.encode() - - -def main(): - key = load_key() - if key is None: - key = generate_key() - save_key(key) - - master_password = get_master_password() - if master_password != key: - print("Master password is incorrect. Exiting...") - return - - passwords = load_passwords(key) - if not os.path.exists(PASSWORD_FILE): - create_passwords_file() - - if not os.path.exists(MASTER_PASSWORD_FILE): - create_master_password_file(master_password.decode()) - - while True: - print("\nMenu:") - print("1. Add Password") - print("2. Get Password") - print("3. Delete Password") - print("4. Exit") - - choice = input("Enter your choice (1/2/3/4): ") - - if choice == "1": - add_password(passwords, key) - elif choice == "2": - get_password(passwords) - elif choice == "3": - delete_password(passwords, key) - elif choice == "4": - break - else: - print("Invalid choice. Please try again.") - - -if __name__ == "__main__": - main() +# This code is made by MRayan Asim +# Packages needed: +# pip install cryptography +# Tou use to follow the 3 steps: +# 1-When you run this code it will ask for the master key you can find the key in the master_password.txt which will create when you run the code +# 2-copy and enter the key and add password with the website name then username or email and at last enter the password +# 3- the password would save in passwrods.json they will be coded so to decode go to get passwords option on the code for this you need to remember the name of the website you want to get the password +print( + """ +1-When you run this code it will ask for the master key you can find the key in the master_password.txt which will create when you run the code +2-copy and enter the key and add password with the website name then username or email and at last enter the password +3- the password would save in passwrods.json they will be coded so to decode go to get passwords option on the code for this you need to remember the name of the website you want to get the password +""" +) +import json +import os +import getpass +from cryptography.fernet import Fernet + +PASSWORD_FILE = os.getenv("PASSWORD_FILE", "passwords.json") +MASTER_PASSWORD_FILE = os.getenv("MASTER_PASSWORD_FILE", "master_password.txt") + + +def generate_key(): + return Fernet.generate_key() + + +def load_key(): + try: + with open(MASTER_PASSWORD_FILE, "rb") as f: + return f.read() + except FileNotFoundError: + return None + + +def save_key(key): + with open(MASTER_PASSWORD_FILE, "wb") as f: + f.write(key) + + +def encrypt_data(data, key): + cipher = Fernet(key) + return cipher.encrypt(data.encode()) + + +def decrypt_data(encrypted_data, key): + cipher = Fernet(key) + return cipher.decrypt(encrypted_data).decode() + + +def load_passwords(key): + try: + with open(PASSWORD_FILE, "rb") as f: + encrypted_data = f.read() + decrypted_data = decrypt_data(encrypted_data, key) + return json.loads(decrypted_data) + except (FileNotFoundError, json.JSONDecodeError): + return {} + + +def save_passwords(passwords, key): + with open(PASSWORD_FILE, "wb") as f: + data = json.dumps(passwords, indent=4) + encrypted_data = encrypt_data(data, key) + f.write(encrypted_data) + + +def create_passwords_file(): + initial_passwords = {} + with open(PASSWORD_FILE, "w") as f: + json.dump(initial_passwords, f, indent=4) + print(f"Created '{PASSWORD_FILE}' with initial content.") + + +def create_master_password_file(master_password): + with open(MASTER_PASSWORD_FILE, "w") as f: + f.write(master_password) + print(f"Created '{MASTER_PASSWORD_FILE}' with the master password.") + + +def add_password(passwords, key): + website = input("Enter website name: ") + username = input("Enter username/email: ") + password = getpass.getpass("Enter password: ") + + passwords[website] = {"username": username, "password": password} + save_passwords(passwords, key) + print("Password added successfully!") + + +def get_password(passwords): + website = input("Enter website name: ") + + if website in passwords: + print(f"Website: {website}") + print(f"Username/Email: {passwords[website]['username']}") + print(f"Password: {passwords[website]['password']}") + else: + print("Password not found for the given website.") + + +def delete_password(passwords, key): + website = input("Enter website name: ") + + if website in passwords: + del passwords[website] + save_passwords(passwords, key) + print("Password deleted successfully!") + else: + print("Password not found for the given website.") + + +def get_master_password(): + master_password = getpass.getpass("Enter master password: ") + return master_password.encode() + + +def main(): + key = load_key() + if key is None: + key = generate_key() + save_key(key) + + master_password = get_master_password() + if master_password != key: + print("Master password is incorrect. Exiting...") + return + + passwords = load_passwords(key) + if not os.path.exists(PASSWORD_FILE): + create_passwords_file() + + if not os.path.exists(MASTER_PASSWORD_FILE): + create_master_password_file(master_password.decode()) + + while True: + print("\nMenu:") + print("1. Add Password") + print("2. Get Password") + print("3. Delete Password") + print("4. Exit") + + choice = input("Enter your choice (1/2/3/4): ") + + if choice == "1": + add_password(passwords, key) + elif choice == "2": + get_password(passwords) + elif choice == "3": + delete_password(passwords, key) + elif choice == "4": + break + else: + print("Invalid choice. Please try again.") + + +if __name__ == "__main__": + main() diff --git a/Utilities/passwrd_generator.py b/Utilities/passwrd_generator.py index aae8f50..09cc1bd 100644 --- a/Utilities/passwrd_generator.py +++ b/Utilities/passwrd_generator.py @@ -3,5 +3,5 @@ passlen = int(input("enter the length of password: ")) s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?" -p = "".join(random.sample(s, passlen)) +p = "".join(random.sample(s, passlen)) # nosec B311 print(p) diff --git a/Utilities/secret_code.py b/Utilities/secret_code.py index 50a25ab..e1ec22f 100644 --- a/Utilities/secret_code.py +++ b/Utilities/secret_code.py @@ -7,7 +7,7 @@ # Function to encode a word def encode_word(word): - encoded_word = "".join(random.sample(word, len(word))) + encoded_word = "".join(random.sample(word, len(word))) # nosec B311 return encoded_word diff --git a/Utilities/url.py b/Utilities/url.py index a814d89..49c2446 100644 --- a/Utilities/url.py +++ b/Utilities/url.py @@ -9,8 +9,12 @@ import qrcode import time +# Default timeout for HTTP requests (seconds) +DEFAULT_TIMEOUT = 10 + def validate_url(url): + """Validate URL format using regular expression.""" # Regular expression pattern for URL validation pattern = re.compile( r"^https?://" # http:// or https:// @@ -22,6 +26,7 @@ def validate_url(url): def analyze_url(url): + """Analyze and validate a URL.""" if validate_url(url): print("URL is valid.") # Perform further analysis or processing here @@ -30,6 +35,7 @@ def analyze_url(url): def shorten_url(url): + """Shorten a URL using pyshorteners.""" # Initialize the URL shortener shortener = pyshorteners.Shortener() @@ -39,16 +45,26 @@ def shorten_url(url): return shortened_url -def is_valid_url(url): +def is_valid_url(url, timeout=DEFAULT_TIMEOUT): + """ + Check if a URL exists and is accessible. + + Args: + url: The URL to check + timeout: Request timeout in seconds (default: 10) + """ # Send a HEAD request to check if the URL exists try: - response = requests.head(url) + # Use timeout to prevent hanging + response = requests.head(url, timeout=timeout) return response.status_code == requests.codes.ok + except requests.Timeout: + return False except requests.exceptions.RequestException: return False -print("This URL code is made by MRayan Asim. Hope you will like this! 😊") +print("This URL code is made by MRayan Asim. Hope you will like this! \ud83d\ude0a") time.sleep(3) # Prompt the user to enter a URL @@ -57,8 +73,12 @@ def is_valid_url(url): # Check if the URL is valid if is_valid_url(url): # Shorten the URL - shortened_url = shorten_url(url) - print("Shortened URL:", shortened_url) + try: + shortened_url = shorten_url(url) + print("Shortened URL:", shortened_url) + except Exception as e: + print(f"Error shortening URL: {e}") + shortened_url = url else: print("Invalid URL")