Skip to content

Instantly share code, notes, and snippets.

@TobeTek
Last active July 9, 2023 01:55
Show Gist options
  • Save TobeTek/6bf3f7da7c3cb9962af711d2d0cd43c8 to your computer and use it in GitHub Desktop.
Save TobeTek/6bf3f7da7c3cb9962af711d2d0cd43c8 to your computer and use it in GitHub Desktop.
Vigenere (Keyword) Cipher - Python
"""
Vignere (Keyword) Cipher implementation in Python
"""
import string
def generate_key(keyword: str, keyletter: str = "A") -> str:
"""
Generate a polyalphabetic cipher key
"""
keyword = [letter.upper() for letter in keyword if letter.isalnum()]
unique = []
for l in keyword:
if l not in unique:
unique.append(l)
keyword = unique
insert_pos = string.ascii_uppercase.index(keyletter)
padding_chars = [
letter for letter in string.ascii_uppercase if letter not in keyword
]
key = padding_chars[:insert_pos] + keyword + padding_chars[insert_pos:]
key = "".join(key)
return key
def encrypt(plain_text: str, key: str) -> str:
"""
Encrypt a plaintext string
"""
cipher_text = []
plain_text = [letter.upper() for letter in plain_text if letter.isalnum()]
for char in plain_text:
indx = string.ascii_uppercase.index(char)
c = key[indx]
cipher_text.append(c)
return "".join(cipher_text)
def decrypt(cipher_text: str, key: str) -> str:
"""
Decrypt ciphertext with a key
"""
plain_text = []
for char in cipher_text:
indx = key.index(char)
c = string.ascii_uppercase[indx]
plain_text.append(c)
return "".join(plain_text)
if __name__ == "__main__":
# plain_text = input("Enter the message: ")
# keyword = input("Enter the keyword: ")
cipher_text = "VIAGUIGTLBILOCSDQN".upper()
keyword = "SHOPIFY COMMERCE".upper()
key = generate_key(keyword)
print(f"{key=}")
# cipher_text = encryption(string,key)
# print("Encrypted message:", encrypt_text)
print("Decrypted message:", decrypt(cipher_text, key))
@PirKate
Copy link

PirKate commented Dec 20, 2022

excuse me, were you doing dev degree/shopify problems? because I was and I found this xDD

@TobeTek
Copy link
Author

TobeTek commented Dec 20, 2022

Hey @PirKate 👋,
Yes, indeed I was. Googled for a Python implementation of keyword ciphers and couldn't find much so I thought I'd share this.
Hope it helps! 🙂

@kamorudeenalo
Copy link

If I am correct, the answer to the first problem is ### WeLoveOurMerchants

@TobeTek
Copy link
Author

TobeTek commented Dec 22, 2022

Sounds right @kamorudeenalo

@miryasha
Copy link

miryasha commented Jan 9, 2023

If I am correct, the answer to the first problem is ### WeLoveOurMerchants

That's what I found too!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment