Created
May 8, 2024 21:56
-
-
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
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
""" | |
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