Advertisement
FocusedWolf

Python: Password Generator

Apr 3rd, 2022 (edited)
569
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.22 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. # Version 25
  4.  
  5. # POSTED ONLINE: https://pastebin.com/g10jVftx
  6.  
  7. # Windows: $ pip install windows-curses pyperclip
  8. #
  9. # Linux:   $ sudo pacman -S python-pyperclip
  10. #          $ sudo pacman -S wl-clipboard    <-- Pyperclip has issues with KDE + Wayland. Installing this seems to get it to work.
  11. #
  12. #          NOTE: For Linux you also need to install a copy/paste mechanism if you don't have one.
  13. #                KDE has /bin/klipper installed by default. For other window managers try [$ sudo pacman -S xclip] or [$ sudo pacman -S xsel].
  14. #
  15. #          NOTE: If you get error "Cannot find '.setClipboardContents' in object /klipper at org.kde.klipper",
  16. #                its because klipper isn't running on startup. Try Start > klipper to see if the problem goes away.
  17. #
  18. #          NOTE: To display klipper in the taskbar, right click the ^ > Configure System Tray... > Entries > Clipboard: [Show when relevant].
  19.  
  20. import curses
  21. import pyperclip
  22. import sys
  23.  
  24. # -----
  25.  
  26. def init_colors():
  27.     # Enable color functionality.
  28.     curses.start_color()
  29.  
  30.     # Define all standard colors with black background.
  31.     curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
  32.     curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
  33.     curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
  34.     curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK)
  35.     curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
  36.     curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)
  37.     curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_BLACK)
  38.  
  39.     # Create variables for easier use.
  40.     global COLOR_RED, COLOR_GREEN, COLOR_YELLOW, COLOR_BLUE, COLOR_MAGENTA, COLOR_CYAN, COLOR_WHITE
  41.     COLOR_RED = curses.color_pair(1)
  42.     COLOR_GREEN = curses.color_pair(2)
  43.     COLOR_YELLOW = curses.color_pair(3)
  44.     COLOR_BLUE = curses.color_pair(4)
  45.     COLOR_MAGENTA = curses.color_pair(5)
  46.     COLOR_CYAN = curses.color_pair(6)
  47.     COLOR_WHITE = curses.color_pair(7)
  48.  
  49. # -----
  50.  
  51. row = 0
  52. col = 0
  53. def writeline(stdscr, text='', color=None):
  54.     global row, col
  55.     lines = text.split('\n')
  56.     for line in lines:
  57.         try:
  58.             stdscr.addstr(row, col, line, color or COLOR_WHITE)
  59.         except curses.error: # Happens with off screen writing.
  60.             pass
  61.         row += 1
  62.         col = 0
  63.  
  64. def write(stdscr, text='', color=None):
  65.     global row, col
  66.     lines = text.split('\n')
  67.     for i, line in enumerate(lines):
  68.         try:
  69.             stdscr.addstr(row, col, line, color or COLOR_WHITE)
  70.         except curses.error: # Happens with off screen writing.
  71.             pass
  72.         if i < len(lines) - 1:
  73.             row += 1
  74.             col = 0
  75.         else:
  76.             col += len(line)
  77.  
  78. def clear(stdscr):
  79.     global row
  80.     global col
  81.     row = 0
  82.     col = 0
  83.     stdscr.clear()
  84.  
  85. # -----
  86.  
  87. def draw_menu(stdscr, menu_items, selected_index, title, highlight):
  88.     # Clear screen.
  89.     clear(stdscr)
  90.  
  91.     if title:
  92.         # Draw title.
  93.         writeline(stdscr, title)
  94.  
  95.     # Draw menu items.
  96.     for i in range(len(menu_items)):
  97.         menuItem = menu_items[i]
  98.         if highlight in menuItem:
  99.             left,right = menuItem.split(highlight)
  100.             write(stdscr, f' {"●" if i == selected_index else "○"} {left}', COLOR_GREEN if i == selected_index else COLOR_CYAN)
  101.             write(stdscr, f'{highlight}', COLOR_RED)
  102.             writeline(stdscr, f'{right}', COLOR_GREEN if i == selected_index else COLOR_CYAN)
  103.         else:
  104.             writeline(stdscr, f' {"●" if i == selected_index else "○"} {menuItem}', COLOR_RED)
  105.  
  106.     # Draw usage information.
  107.     writeline(stdscr)
  108.     writeline(stdscr, ' Make → Space', COLOR_YELLOW)
  109.     writeline(stdscr, ' Copy → Enter', COLOR_YELLOW)
  110.     writeline(stdscr, ' Rise → Up', COLOR_YELLOW)
  111.     writeline(stdscr, ' Fall → Down', COLOR_YELLOW)
  112.     writeline(stdscr, ' Smol → Left', COLOR_YELLOW)
  113.     writeline(stdscr, ' Swol → Right', COLOR_YELLOW)
  114.     writeline(stdscr, ' Zoom → Ctrl+/-', COLOR_YELLOW)
  115.     writeline(stdscr, ' Quit → Esc', COLOR_YELLOW)
  116.  
  117.     # Redraw screen.
  118.     stdscr.refresh()
  119.  
  120. # -----
  121.  
  122. import string
  123.  
  124. # Character groups to be used in the password.
  125. CHARACTER_GROUPS = [
  126.     string.ascii_lowercase,
  127.     string.ascii_uppercase,
  128.     string.digits,
  129.     #string.punctuation,
  130.     '!@#$%^&*()', # PayPal allowed punctuation characters.
  131. ]
  132.  
  133. PASSWORD_CHARACTERS = ''.join(CHARACTER_GROUPS)
  134.  
  135. # Remove unwanted characters.
  136. removal_table = str.maketrans('', '', r'|\\/`\'\"')
  137. PASSWORD_CHARACTERS = PASSWORD_CHARACTERS.translate(removal_table)
  138.  
  139. # Remove timestamp divider characters so they can be uniquely added to the password around the timestamp.
  140. TIMESTAMP_DIVIDER_LEFT = '('
  141. TIMESTAMP_DIVIDER_RIGHT = ')'
  142. PASSWORD_CHARACTERS = PASSWORD_CHARACTERS.replace(TIMESTAMP_DIVIDER_LEFT, '').replace(TIMESTAMP_DIVIDER_RIGHT, '')
  143.  
  144. from datetime import datetime
  145. import secrets
  146. def generate_timestamped_passwords(password_length, count=5):
  147.     dt = datetime.now()
  148.     short_time_stamp = f"{TIMESTAMP_DIVIDER_LEFT}{dt.strftime('%y%m%d')}{TIMESTAMP_DIVIDER_RIGHT}"
  149.     short_time_stamp_len = len(short_time_stamp)
  150.     passwords = []
  151.     retries = 100000
  152.     for _ in range(count):
  153.         for attempt in range(retries):
  154.             # SOURCE: https://docs.python.org/3/library/secrets.html
  155.             password = ''.join(secrets.choice(PASSWORD_CHARACTERS) for _ in range(password_length - short_time_stamp_len))
  156.  
  157.             # If the password has repeating characters.
  158.             # NOTE: The non-timestamped password is tested because the timestamp might fail the unique-segments test depending on what day it is.
  159.             if not has_unique_segments(password):
  160.                 continue
  161.  
  162.             # If the password uses characters from all categories.
  163.             if has_representative_characters(password):
  164.                 timestamped_password = shuffle(password, short_time_stamp)
  165.                 passwords.append(timestamped_password)
  166.                 break
  167.         else:
  168.             passwords.append(f'ERROR: Failed to generate a valid password after {retries} attempts.')
  169.  
  170.     large_time_stamp = f' Created: {dt.strftime("%Y-%m-%d %H:%M:%S")}\n'
  171.     large_time_stamp += f' Length: {password_length}\n'
  172.     return passwords, large_time_stamp, short_time_stamp
  173.  
  174. # -----
  175.  
  176. def has_representative_characters(s):
  177.     min_characters_per_group = min(4, len(s) // len(CHARACTER_GROUPS))
  178.     for group in CHARACTER_GROUPS:
  179.         if sum(char in group for char in s) < min_characters_per_group:
  180.             return False
  181.     return True
  182.  
  183. def has_unique_segments(s):
  184.     segment_length = 2 if len(s) > 80 else 10
  185.     for i in range(0, len(s), segment_length):
  186.         segment = s[i:i + segment_length]
  187.         if len(set(segment)) != len(segment):
  188.             return False
  189.     return True
  190.  
  191. # -----
  192.  
  193. # Insert a word into a sentence randomly.
  194. def shuffle(sentence, word):
  195.     max_word_index = len(sentence)
  196.  
  197.     # Generate a random integer in the range [0, n).
  198.     random_index = secrets.randbelow(max_word_index + 1)
  199.  
  200.     # Insert the word into the sentence.
  201.     return sentence[:random_index] + word + sentence[random_index:]
  202.  
  203. # -----
  204.  
  205. def wait_for_any_keypress(stdscr):
  206.     writeline(stdscr, ' Press any key to continue . . . ')
  207.     stdscr.refresh()
  208.  
  209.     try:
  210.         # Get keyboard input.
  211.         stdscr.getch()
  212.     except KeyboardInterrupt:
  213.         sys.exit()
  214.  
  215. # -----
  216.  
  217. MIN_PASSWORD_LENGTH = 12 # 6 numbers (timestamp) + 2 uppercase letters + 2 lowercase letters + 2 punctuation (timestamp-dividers).
  218.  
  219. def main(stdscr):
  220.     init_colors()
  221.  
  222.     password_length = 23
  223.     menu_items, large_time_stamp, short_time_stamp = generate_timestamped_passwords(password_length)
  224.     selected_index = 0
  225.  
  226.     draw_menu(stdscr, menu_items, selected_index, large_time_stamp, short_time_stamp) # Initial drawing.
  227.  
  228.     try:
  229.         while True:
  230.             # Get keyboard input.
  231.             key = stdscr.getch()
  232.  
  233.             # If Escape key is pressed.
  234.             if key == ord('\x1b'):
  235.                 break
  236.  
  237.             # If Space key is pressed.
  238.             elif key == ord(' '):
  239.                 menu_items, large_time_stamp, short_time_stamp = generate_timestamped_passwords(password_length)
  240.  
  241.             # If Up key is pressed.
  242.             elif key == curses.KEY_UP:
  243.                 # Loop around backwards.
  244.                 selected_index = (selected_index - 1 + len(menu_items)) % len(menu_items)
  245.  
  246.             # If Down key is pressed.
  247.             elif key == curses.KEY_DOWN:
  248.                 # Loop around forwards.
  249.                 selected_index = (selected_index + 1) % len(menu_items)
  250.  
  251.             # If Left key is pressed.
  252.             elif key == curses.KEY_LEFT:
  253.                 # Reduce length of passwords.
  254.                 password_length = max(MIN_PASSWORD_LENGTH, password_length - 1)
  255.                 menu_items, large_time_stamp, short_time_stamp = generate_timestamped_passwords(password_length)
  256.  
  257.             # If Right key is pressed.
  258.             elif key == curses.KEY_RIGHT:
  259.                 # Increase length of passwords.
  260.                 password_length += 1
  261.                 menu_items, large_time_stamp, short_time_stamp = generate_timestamped_passwords(password_length)
  262.  
  263.             # If Enter key is pressed.
  264.             # NOTE: On Windows the enter key appears to be \r, and on Linux its \n.
  265.             elif key in (curses.KEY_ENTER, ord('\r'), ord('\n')):
  266.                 pyperclip.copy(menu_items[selected_index])
  267.                 writeline(stdscr, f"\n Copied {menu_items[selected_index]} to clipboard.\n")
  268.                 wait_for_any_keypress(stdscr)
  269.  
  270.             # Else an unexpected key is pressed.
  271.             #  else:
  272.             #      try:
  273.             #          writeline(stdscr, "\n The pressed key '{}' {} is not associated with a menu function.\n".format(chr(key), key))
  274.             #      except ValueError:
  275.             #          writeline(stdscr, "\n The pressed key {} is not associated with a menu function.\n".format(key))
  276.             #      wait_for_any_keypress(stdscr)
  277.  
  278.             draw_menu(stdscr, menu_items, selected_index, large_time_stamp, short_time_stamp)
  279.     except KeyboardInterrupt:
  280.         sys.exit()
  281.  
  282. if __name__ == '__main__':
  283.     curses.wrapper(main)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement