Skip to content

Instantly share code, notes, and snippets.

@Kenny2github
Created July 25, 2019 16:28
Show Gist options
  • Select an option

  • Save Kenny2github/99a368fe0d363d70a2966682d553f791 to your computer and use it in GitHub Desktop.

Select an option

Save Kenny2github/99a368fe0d363d70a2966682d553f791 to your computer and use it in GitHub Desktop.
Transform text with the vigenere cipher.
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def vigenere(string, key, direction=1):
"""Transform text with the vigenere cipher.
``string`` is the text to transform.
``key`` is the key to use in the process.
``direction`` is the direction of transformation:
1 for encoding, and -1 for decoding.
Return value is the transformed text.
"""
result = ''
string, key = string.upper(), key.upper()
key = (key * (len(string) // len(key) + 1))[:len(string)]
j = 0
for i in string:
idx = LETTERS.find(i)
if idx == -1:
result += i
continue
idx += LETTERS.find(key[j]) * direction
idx %= len(LETTERS)
result += LETTERS[idx]
j += 1
return result
def envigenere(string, key):
"""Encode text with the vigenere cipher.
``string`` is the text to encode.
``key`` is the key to use in encoding.
Equivalent to vigenere(string, key, 1)
Return value is the encoded text.
"""
return vigenere(string, key, 1)
def devigenere(string, key):
"""Decode text encoded with the vigenere cipher.
``string`` is the text to decode.
``key`` is the key used in encoding.
Equivalent to vigenere(string, key, -1)
Return value is the decoded text.
"""
return vigenere(string, key, -1)
if __name__ == '__main__':
edq = ''
while edq != 'q':
edq = input('Do you want to [e]ncode, [d]ecode, or [q]uit? ')
if edq == 'e':
print(envigenere(input('Text: '), input('Key: ')))
elif edq == 'd':
print(devigenere(input('Text: '), input('Key: ')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment