-2
from random import shuffle  

alphabet="abcdefghijklmnopqrstuvwxyz"  

def substitution(alphabet,plaintext):  

    # Create array to use to randomise alphabet position  
    randarray=range(0,len(alphabet))  
    shuffle(randarray)  

    key="Zebra"  

    #Create our substitution dictionary  
    dic={}  
    for i in range(0,len(alphabet)):  
        key+=alphabet[randarray[i]]  
        dic[alphabet[i]]=alphabet[randarray[i]]  

    #Convert each letter of plaintext to the corrsponding  
    #encrypted letter in our dictionary creating the cryptext  
    ciphertext=""  
    for l in plaintext:  
        if l in dic:  
            l=dic[l]  
        ciphertext+=l  
    for i in alphabet:  
        print i,  
    print  
    for i in key:  
        print i,  
    print  
    return ciphertext,key  

# This function decodes the ciphertext using the key and creating  
# the reverse of the dictionary created in substitution to retrieve  
# the plaintext again  
def decode(alphabet,ciphertext,key):  

    dic={}  
    for i in range(0,len(key)):  
        dic[key[i]]=alphabet[i]  

    plaintext=""  
    for l in ciphertext:  
        if l in dic:  
            l=dic[l]  
        plaintext+=l  

    return plaintext  

# Example useage  
plaintext="the cat sat on the mat"  
ciphertext,key=substitution(alphabet,plaintext)  
print "Key: ", key  
print "Plaintext:", plaintext  
print "Cipertext:", ciphertext  
print "Decoded  :", decode(alphabet,ciphertext,key)

When I run this code, it returns a "IndexError: String index out of range" error. Could someone give me hand troubleshooting it, I can't see the problem.

Traceback (most recent call last):
  File"/Users/Devlin/Desktop/Dev/Python/Substitution Cypher.py", line 57, in 
    print "Decoded :", decode(alphabet,ciphertext,key)
  File "/Users/Devlin/Desktop/Dev/Python/Substitution Cypher.py", line 41, in decode
    dic[key[i]]=alphabet[i] IndexError: string index out of range
4

2 回答 2

0

问题出在这里:

def decode(alphabet,ciphertext,key):  
    dic={}  
    for i in range(0,len(key)):  
        dic[key[i]]=alphabet[i] # this line fails

key此时始终是 31 个字符,即len('Zebra') + len(alphabet). 与len(alphabet)往常一样 26,alphabet[i]当 i > 25 时失败。

我相信您误解了key这里所代表的内容。substitution应该产生一个随机密钥,它不是密码或任何类型的盐。事实上,如果您查看从 获得此代码的原始文章,您会看到它是key=""insubstitution而不是 some-random-value。

于 2012-09-04T05:52:30.363 回答
0
for i in range(0,len(key)):  
    dic[key[i]]=alphabet[i] 

在这里,len(key) == len(alphabet) + 5。因此,i(迭代range(0, len(key)))比字母表的实际长度更远。这是由于部分

key="Zebra"  #HERE, YOU START WITH ZEBRA

#Create our substitution dictionary  
dic={}  
for i in range(0,len(alphabet)):  
    key+=alphabet[randarray[i]]  #AND HERE, YOU ADD TO ZEBRA
    dic[alphabet[i]]=alphabet[randarray[i]]  

所以,再一次,你得到的字符key比 in 多alphabet,这会导致错误。

解决办法是换线

key="Zebra"

key=""

你为什么要它是“斑马”呢?

* PSrange(x)与 相同range(0, x),所以你通常应该只写range(len(key))etc... *

于 2012-09-04T05:52:42.193 回答