Skip to content

Instantly share code, notes, and snippets.

@kaecy
Created October 7, 2023 20:30
Show Gist options
  • Save kaecy/7f7ca4a1db346bbeb1ce21aca3e72fb1 to your computer and use it in GitHub Desktop.
Save kaecy/7f7ca4a1db346bbeb1ce21aca3e72fb1 to your computer and use it in GitHub Desktop.
A basic Vigenere encryption utility
# usage: vigenere.py [-h] [--key KEY] [--decrypt] string
#
# exmaple:
# >vigenere.py HELLO
# output: DEWVP
#
# >vigenere.py --decrypt DEWVP
# output: HELLO
#
# positional arguments:
# string the str to encrypt or decrypt
#
# options:
# -h, --help show this help message and exit
# --key KEY use a different key
# --decrypt decrypt text
english_alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def vigenere(text, key, decrypt=False):
text = text.upper()
key = key.upper()
encrypted_text = ""
KEYLEN = len(key)
keyIndex = 0
for i in range(len(text)):
t = ord(text[i]) - 65
k = ord(key[keyIndex]) - 65
if text[i] == " ":
encrypted_text += " "
continue
if decrypt == False:
encrypted_text += english_alphabet[(t + k) % 26 ]
else:
encrypted_text += english_alphabet[(t - k) % 26 ]
keyIndex += 1
if keyIndex == KEYLEN: keyIndex = 0
return encrypted_text
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("string", help="the str to encrypt or decrypt")
parser.add_argument("--key", help="use a different key")
parser.add_argument("--decrypt", help="decrypt text", action="store_true")
args = parser.parse_args()
text = args.string
key = args.key or "WALKBYME"
if args.decrypt:
clear_text = vigenere(text, key, True)
print(clear_text)
else:
cypher_text = vigenere(text, key)
print(cypher_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment