Last active
July 9, 2023 01:55
-
-
Save TobeTek/6bf3f7da7c3cb9962af711d2d0cd43c8 to your computer and use it in GitHub Desktop.
Vigenere (Keyword) Cipher - Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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)) |
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! ๐
If I am correct, the answer to the first problem is ### WeLoveOurMerchants
Sounds right @kamorudeenalo
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
excuse me, were you doing dev degree/shopify problems? because I was and I found this xDD