Skip to content

Instantly share code, notes, and snippets.

@aminzabardast
Created May 8, 2024 21:56
Show Gist options
  • Save aminzabardast/d68fafac9b0521b523e6aa9dcb20411b to your computer and use it in GitHub Desktop.
Save aminzabardast/d68fafac9b0521b523e6aa9dcb20411b to your computer and use it in GitHub Desktop.
Example of Known Plain-text Attack (KPA) to break Vigenère's Cipher
"""
Using Known Plain-text Attack (KPA) to break Vigenère's Cipher
Check the following link to know more about the Vigenère's Cipher, including how to use KPA to break the encryption.
https://www.commonlounge.com/vigeneres-cipher-b27ffb470c3a4d2b83378edee0a55dab/
"""
import re
import string
plain_text = "This is a sample text. Or is it?!?!"
cyphered_text = "ffswgeycekbjoxcjryvgegd"
def remove_gunk(text):
"""
Remove any none alphabetical characters
"""
return re.sub(r"[^a-z]", "", text.lower(), 0, re.MULTILINE)
def convert_to_numbers(text):
"""
Converts character to number. a -> 1, b -> 2, ... z -> 26
"""
return list(map(lambda x: string.ascii_lowercase.index(x) + 1, text))
def KPA(plain_text, cyphered_text):
"""
Known Plain-text Attack
"""
pt = convert_to_numbers(remove_gunk(plain_text))
ct = convert_to_numbers(remove_gunk(cyphered_text))
result = []
for i in range(len(ct)):
letter_location = (ct[i] - pt[i]) % 26
ascii = chr(letter_location + 1 + 96)
result.append(ascii)
print(''.join(result))
KPA(plain_text, cyphered_text)
# This will print 'mykeymykeymykeymykeymyk'. You can deduce from this that the key is 'mykey'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment