Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add: vigenere cipher #2094

Merged
merged 1 commit into from
Jan 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions vigenere_cipher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
text = "mrttaqrhknsw ih puggrur"
custom_key = "happycoding"


def vigenere(message, key, direction=1):
key_index = 0
alphabet = "abcdefghijklmnopqrstuvwxyz"
final_message = ""

for char in message.lower():
# Append any non-letter character to the message
if not char.isalpha():
final_message += char
else:
# Find the right key character to encode/decode
key_char = key[key_index % len(key)]
key_index += 1

# Define the offset and the encrypted/decrypted letter
offset = alphabet.index(key_char)
index = alphabet.find(char)
new_index = (index + offset * direction) % len(alphabet)
final_message += alphabet[new_index]

return final_message


def encrypt(message, key):
return vigenere(message, key)


def decrypt(message, key):
return vigenere(message, key, -1)


print(f"\nEncrypted text: {text}")
print(f"Key: {custom_key}")
decryption = decrypt(text, custom_key)
print(f"\nDecrypted text: {decryption}\n")
Loading