2

Here's a small piece of code in python that may be helpful to those who like to play with substitution ciphers.....
Say we have a text that is ciphered with simple substitution cipher, and say we know that the original text contained a certain phrase...but all we have now is a ciphered text and we don't know where is that phrase in the text. On the other hand, if we knew what part of ciphered text represents that certain phrase, that could be a great help for deciphering the text. Here's a simple code that can do that...feel free to modify and use it on your own..

    def relation(word):

        def inner(w,m,n, rel=""):
            if m>=len(w):
                return rel
            if  n>=len(w):
                return inner(w,m+1,m+1,rel)
            else:
                if  w[m]==w[n]:
                    rel+="1"
                    return inner(w,m,n+1,rel)
                else:
                    rel+="0"
                    return inner(w,m,n+1,rel)

        return inner(word, 0, 0, "")

    def check(text, word):
        for i in range(len(text)):
            sub=text[i:i+len(word)]
            if relation(sub) == relation(word):
                result.write( sub+"  ===>  "+word + "\n" )



    word = raw_input("enter the word: ")

    with open("example.txt", "r") as text:
            with open("result.txt", "a") as result:
                    for line in text:
                            textLine=line.strip(" ").strip("\n")
                            check(textLine,word)

You need to place your ciphered text in a text file ("example.txt").
For start you could use this ciphered text:

UJEJVZRQFEYGESVSOOFSUJWIGFEESTGUFVVZG
UJJEJCFWFQFEVLGWVSWPZSIZFNASVVGESWNQFEVR
PFOVFYSWNQAFIGFVQEGISOGARVZGOFLGLJLGWV
F XGFKVSCKAXKVTFIKJKOOZJPNSEAFEESTGUFVVZG
UJJE
CJEFLJLGWVVZGEGPFOZGOSVFVSJWJWXJVZOSUGO
FWUVZGWVZGOZJPNSEAOVGQQGUXFIYVJLFYGPFR
OFRSWNFNGXGCJEGXGFKVR
WJVFVFAAOFSUUJEJVZRQFEYGEOFSASWN
VZEJKNZQGFEAOXGCJEGOPSWG

Try this text in the code....we know that this text contains the phrase "for a moment there was hesitation". But note that the ciphered text doesn't contain spaces, so you must use this phrase "foramomenttherewashesitation"

I know, it's not a big deal to do so with substitution ciphers as there's a powerful method; frequency analysis....but, however, this can be helpful in some cases...

Please, don't laught at me if the code is too simple...I'm just a newbie....

Edited by vunkas

2
Contributors
1
Reply
47
Views
3 Years
Discussion Span
Last Post by nosrac25
1
mess = open('data.file').read() 
#insert the data file
clean = mess.translate(None, '!@#$%^&*()_+').replace('then','now')
#ignores all characters you put in and replaces then with now
print clean

Edited by nosrac25

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.