使用凯撒密码解码加密文件



我想解密一个加密文件。 在转换它并将其与字典(充满单词(进行比较时,我一直在底部遇到麻烦。 有人可以引导我朝着正确的方向前进吗? 我正在努力比较两者。

#this function takes a string and encrypts ONLY letters by k shifts
def CaeserCipher(string, k):
    #setting up variables to move through
    upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'*10000
    lower = 'abcdefghijklmnopqrstuvwxyz'*10000
    newCipher = ''
    #looping each letter and moving it k times
    for letter in string:
        if letter in upper:
            if upper.index(letter) + k > 25:
                indexPosition = (upper.index(letter) + k) 
                newCipher = newCipher + upper[indexPosition]
            else:
                indexPosition = upper.index(letter) + k
                newCipher = newCipher + upper[indexPosition]
        elif letter in lower:
            if lower.index(letter) + k > 25:
                indexPosition = (lower.index(letter) + k)  
                newCipher = newCipher + lower[indexPosition]
            else:
                indexPosition = lower.index(letter) + k
                newCipher = newCipher + lower[indexPosition]
        else:
            newCipher = newCipher + letter

    return newCipher
f = open('dictionary.txt', "r")
dictionary = set()
for line in f:
    word = line.strip()
    dictionary.add(word)
print dictionary
#main file
#reading file and encrypting text
f = open('encryptMystery1.txt')
string = ''
out = open("plain1.txt", "w")
myList = []
for line in f:
    myList.append(line)
for sentence in myList:
    for k in range(26):
        updatedSentence = CaeserCipher(sentence, k)
        for word in updatedSentence.split():
            if word in dictionary:
                out.write(updatedSentence)
                break
print myList
f.close()
out.close()        

让我们分步解决这个问题,第一步的标题是

为什么凯撒密码中有 260,000 个字符的长字符串

对不起,我不是故意过于戏剧化,但你意识到这将占用更多的空间,嗯,太空,不是吗?这是完全没有必要的。这是一个丑陋而缓慢的黑客,以避免理解%(模(运算符。别这样。

现在,到模数:

第二步当然是理解模数。这实际上并不难,就像除法问题的其余部分一样。你还记得你在学校的时候,只是学习部门吗? 7/4 1r3不是1.75,记得吗?好吧,Python有所有这些功能。 7/4 == 1.757//4 == 17 % 4 == 3。这很有用,因为它可以用于将数字"包装"在固定长度周围。

例如,假设您有一些包含 26 个索引的字符串(例如,我不知道,一个字母表?您正在尝试向起始索引添加一些数字,然后返回结果,但是您将 2 添加到Y并且不起作用!好吧,用模数它可以。 Y 在索引 24 中(记住零是它自己的索引(,24+2 是 26,没有第 26 个索引。但是,如果您知道字符串中只有 26 个元素,我们可以取模并使用 THAT。

按照这个逻辑,index + CONSTANT % len(alphabet)总是使用简单的数学返回正确的数字,而不是你刚刚屠宰的四分之一百万元素长字符串的甜蜜宝贝耶稣。

呃,妈会感到羞耻的。

反转凯撒密码

所以你有一个好主意,依次浏览每一行并对其应用各种密码。如果我是你,我会将它们全部转储到单独的文件中,甚至转储到单独的列表元素中。请记住,如果您要反转密码,则需要使用-k而不是k。不过,简单地更改您的 Caesar 密码来检测它可能是一个好主意,因为模数技巧在这种情况下不起作用。尝试类似操作:

def cipher(text, k):
    cipherkey = "SOMESTRINGGOESHERE"
    if k < 0:
        k = len(cipherkey) + k
        # len(cipherkey) - abs(k) would be more clear, but if it HAS to be
        # a negative number to get in here, it seems silly to add the call
        # to abs

然后你可以做:

startingtext = "Encrypted_text_goes_here"
possibledecrypts = [cipher(startingtext, -i) for i in range(1,26)]

最新更新