Advertisement
ifigazsi

Caesar / Vigenere cypher

Apr 22nd, 2024 (edited)
572
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. from string import ascii_lowercase
  2.  
  3. abc = ascii_lowercase
  4.  
  5. def caesar_code(message, shift):
  6.     output = ""
  7.     shift = shift % len(abc)
  8.     for char in message.lower():
  9.         output += char if char not in abc else _find_shifted_letter(char, shift)
  10.     return output
  11.  
  12.  
  13. def _find_shifted_letter(letter, shift):
  14.     index = abc.index(letter) + shift
  15.     index = index if index < len(abc) else index - len(abc)
  16.     return abc[index]
  17.  
  18.  
  19. def vigenere_encode(message, code):
  20.     code_gen = _code_generator(code)
  21.     output = ""
  22.     for letter in message.lower():
  23.         output += letter if letter not in abc else caesar_code(next(code_gen), abc.index(letter))
  24.     return output
  25.  
  26.  
  27. def vigenere_decode(message, code):
  28.     code_gen = _code_generator(code)
  29.     output = ""
  30.     for letter in message.lower():
  31.         output += letter if letter not in abc else caesar_code("a", abc.index(letter) - abc.index(next(code_gen)))
  32.     return output
  33.  
  34. def _code_generator(code):
  35.     i = 0
  36.     while True:
  37.         yield code[i % len(code)].lower()
  38.         i += 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement