Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # Version 23
- # POSTED ONLINE: https://pastebin.com/g10jVftx
- # Windows: $ pip install pyperclip asciimatics
- #
- # Linux: $ sudo pacman -S python-pyperclip
- # $ sudo pacman -S wl-clipboard <-- Pyperclip has issues with KDE + Wayland. Installing this seems to get it to work.
- # $ yay -S python-asciimatics
- #
- # NOTE: For Linux you also need to install a copy/paste mechanism if you don't have one.
- # KDE has /bin/klipper installed by default. For other window managers try [$ sudo pacman -S xclip] or [$ sudo pacman -S xsel].
- #
- # NOTE: If you get error "Cannot find '.setClipboardContents' in object /klipper at org.kde.klipper",
- # its because klipper isn't running on startup. Try Start > klipper to see if the problem goes away.
- #
- # NOTE: To display klipper in the taskbar, right click the ^ > Configure System Tray... > Entries > Clipboard: [Show when relevant].
- import pyperclip
- from asciimatics.screen import Screen
- from asciimatics.event import KeyboardEvent
- # -----
- def draw_menu(screen, menuItems, selectedIndex, title, highlight):
- # Clear screen.
- clear(screen)
- # Draw title.
- if title:
- writeline(screen, title)
- # Draw menu items.
- for i in range(len(menuItems)):
- menuItem = menuItems[i]
- if highlight in menuItem:
- left,right = menuItem.split(highlight)
- write(screen, f' {"●" if i == selectedIndex else "○"} {left}', Screen.COLOUR_GREEN if i == selectedIndex else Screen.COLOUR_CYAN)
- write(screen, f'{highlight}', Screen.COLOUR_RED)
- writeline(screen, f'{right}', Screen.COLOUR_GREEN if i == selectedIndex else Screen.COLOUR_CYAN)
- else:
- writeline(screen, f' {"●" if i == selectedIndex else "○"} {menuItem}', Screen.COLOUR_RED)
- # Draw usage information.
- writeline(screen)
- writeline(screen, ' Make → Space', Screen.COLOUR_YELLOW)
- writeline(screen, ' Copy → Enter', Screen.COLOUR_YELLOW)
- writeline(screen, ' Rise → Up', Screen.COLOUR_YELLOW)
- writeline(screen, ' Fall → Down', Screen.COLOUR_YELLOW)
- writeline(screen, ' Smol → Left', Screen.COLOUR_YELLOW)
- writeline(screen, ' Swol → Right', Screen.COLOUR_YELLOW)
- writeline(screen, ' Zoom → Ctrl+/-', Screen.COLOUR_YELLOW)
- writeline(screen, ' Quit → Esc', Screen.COLOUR_YELLOW)
- # Draw screen.
- screen.refresh()
- # -----
- row = 0
- col = 0
- def writeline(screen, text='', color=Screen.COLOUR_WHITE):
- global row
- global col
- lines = text.split('\n')
- for i, line in enumerate(lines):
- screen.print_at(line, col, row, color)
- row += 1
- col = 0
- def write(screen, text='', color=Screen.COLOUR_WHITE):
- global row
- global col
- lines = text.split('\n')
- for i, line in enumerate(lines):
- screen.print_at(line, col, row, color)
- if i < len(lines) - 1:
- row += 1
- col = 0
- else:
- col += len(line)
- def clear(screen):
- global row
- global col
- row = 0
- col = 0
- screen.clear()
- # -----
- import string
- # Character groups to be used in the password.
- CHARACTER_GROUPS = [
- string.ascii_lowercase,
- string.ascii_uppercase,
- string.digits,
- string.punctuation,
- #'!@#$%^&*()', # PayPal allowed punctuation characters.
- ]
- PASSWORD_CHARACTERS = ''.join(CHARACTER_GROUPS)
- # Remove unwanted characters.
- removal_table = str.maketrans('', '', r'|\\/`\'\"')
- PASSWORD_CHARACTERS = PASSWORD_CHARACTERS.translate(removal_table)
- # Remove timestamp divider characters so they can be uniquely added to the password around the timestamp.
- TIMESTAMP_DIVIDER_LEFT = '('
- TIMESTAMP_DIVIDER_RIGHT = ')'
- PASSWORD_CHARACTERS = PASSWORD_CHARACTERS.replace(TIMESTAMP_DIVIDER_LEFT, '').replace(TIMESTAMP_DIVIDER_RIGHT, '')
- from datetime import datetime
- import secrets
- def generate_timestamped_passwords(password_length, count=5):
- dt = datetime.now()
- short_time_stamp = f"{TIMESTAMP_DIVIDER_LEFT}{dt.strftime('%y%m%d')}{TIMESTAMP_DIVIDER_RIGHT}"
- short_time_stamp_len = len(short_time_stamp)
- passwords = []
- retries = 100000
- for _ in range(count):
- for attempt in range(retries):
- # SOURCE: https://docs.python.org/3/library/secrets.html
- password = ''.join(secrets.choice(PASSWORD_CHARACTERS) for _ in range(password_length - short_time_stamp_len))
- # If the password has repeating characters.
- # NOTE: The non-timestamped password is tested because the timestamp might fail the unique-segments test depending on what day it is.
- if not has_unique_segments(password):
- continue
- # If the password uses characters from all categories.
- if has_representative_characters(password):
- timestamped_password = shuffle(password, short_time_stamp)
- passwords.append(timestamped_password)
- break
- else:
- passwords.append(f'ERROR: Failed to generate a valid password after {retries} attempts.')
- large_time_stamp = f' Created: {dt.strftime("%Y-%m-%d %H:%M:%S")}\n'
- large_time_stamp += f' Length: {password_length}\n'
- return passwords, large_time_stamp, short_time_stamp
- # -----
- def has_representative_characters(s):
- min_characters_per_group = min(4, len(s) // len(CHARACTER_GROUPS))
- for group in CHARACTER_GROUPS:
- if sum(char in group for char in s) < min_characters_per_group:
- return False
- return True
- def has_unique_segments(s):
- segment_length = 2 if len(s) > 80 else 10
- for i in range(0, len(s), segment_length):
- segment = s[i:i + segment_length]
- if len(set(segment)) != len(segment):
- return False
- return True
- # -----
- # Insert a word into a sentence randomly.
- def shuffle(sentence, word):
- max_word_index = len(sentence)
- # Generate a random integer in the range [0, n).
- random_index = secrets.randbelow(max_word_index + 1)
- # Insert the word into the sentence.
- sentence = sentence[:random_index] + word + sentence[random_index:]
- return sentence
- # -----
- def wait_for_enter_keypress(screen):
- writeline(screen, ' Press ENTER to continue . . . ')
- screen.refresh()
- while True:
- # Get keyboard input.
- screen.wait_for_input(5) # Sleep for this many seconds while waiting for input to prevent 100% CPU usage from the loop.
- ev = screen.get_event()
- if not isinstance(ev, KeyboardEvent):
- continue
- # If Enter key is pressed.
- # NOTE: On Windows the enter key appears to be \r, and on Linux its \n.
- if ev.key_code == ord('\r') or ev.key_code == ord('\n'):
- break
- def wait_for_any_keypress(screen):
- writeline(screen, ' Press any key to continue . . . ')
- screen.refresh()
- while True:
- # Get keyboard input.
- screen.wait_for_input(5) # Sleep for this many seconds while waiting for input to prevent 100% CPU usage from the loop.
- ev = screen.get_event()
- if isinstance(ev, KeyboardEvent):
- break
- # -----
- MIN_PASSWORD_LENGTH = 12 # 6 numbers (timestamp) + 2 uppercase letters + 2 lowercase letters + 2 punctuation (timestamp-dividers).
- def main(screen):
- password_length = 32
- menuItems, large_time_stamp, short_time_stamp = generate_timestamped_passwords(password_length)
- selectedIndex = 0
- draw_menu(screen, menuItems, selectedIndex, large_time_stamp, short_time_stamp) # Initial drawing.
- while True:
- # Get keyboard input.
- screen.wait_for_input(5) # Sleep for this many seconds while waiting for input to prevent 100% CPU usage from the loop.
- ev = screen.get_event()
- if not isinstance(ev, KeyboardEvent):
- continue
- # If Escape key is pressed.
- elif ev.key_code == -1:
- break
- # If Space key is pressed.
- elif ev.key_code == ord(' '):
- menuItems, large_time_stamp, short_time_stamp = generate_timestamped_passwords(password_length)
- # If Up key is pressed.
- elif ev.key_code == Screen.KEY_UP:
- # Loop around backwards.
- selectedIndex = (selectedIndex - 1 + len(menuItems)) % len(menuItems)
- # If Down key is pressed.
- elif ev.key_code == Screen.KEY_DOWN:
- # Loop around forwards.
- selectedIndex = (selectedIndex + 1) % len(menuItems)
- # If Left key is pressed.
- elif ev.key_code == Screen.KEY_LEFT:
- # Reduce length of passwords.
- password_length = max(MIN_PASSWORD_LENGTH, password_length - 1)
- menuItems, large_time_stamp, short_time_stamp = generate_timestamped_passwords(password_length)
- # If Right key is pressed.
- elif ev.key_code == Screen.KEY_RIGHT:
- # Increase length of passwords.
- password_length = password_length + 1
- menuItems, large_time_stamp, short_time_stamp = generate_timestamped_passwords(password_length)
- # If Enter key is pressed.
- # NOTE: On Windows the enter key appears to be \r, and on Linux its \n.
- elif ev.key_code == ord('\r') or ev.key_code == ord('\n'):
- pyperclip.copy(menuItems[selectedIndex])
- writeline(screen, f"\n Copied {menuItems[selectedIndex]} to clipboard.\n")
- wait_for_enter_keypress(screen)
- # Else an unexpected key is pressed.
- # else:
- # try:
- # writeline(screen, "\n The pressed key '{}' {} is not associated with a menu function.\n".format(chr(ev.key_code), ev.key_code))
- # except ValueError:
- # writeline(screen, "\n The pressed key {} is not associated with a menu function.\n".format(ev.key_code))
- # wait_for_any_keypress(screen)
- draw_menu(screen, menuItems, selectedIndex, large_time_stamp, short_time_stamp)
- if __name__ == '__main__':
- Screen.wrapper(main)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement