Skip to content

Commit

Permalink
Merge pull request #2094 from NitkarshChourasia/testing
Browse files Browse the repository at this point in the history
add: vigenere cipher
  • Loading branch information
geekcomputers authored Jan 12, 2024
2 parents 3118ee4 + bae3af2 commit 6377bd9
Showing 1 changed file with 39 additions and 0 deletions.
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")

0 comments on commit 6377bd9

Please sign in to comment.