Vigenere Cipher - 不给信件

时间:2016-05-11 17:02:05

标签: python python-3.x encryption vigenere

我正在尝试在python中创建Vigenere密码。我在互联网上发现了一些代码,因为它很难解决。当我运行此代码时:

plaintext = "HELLO WORLD"
keyword = "KEYKEYKEYKEY"
encoded = ""

for c in range(len(plaintext)):
    char = ord(plaintext[c])
    temp = ord(keyword[c])
    newchar = char + temp
    if newchar > ord("Z"):
        newchar -= 26
    newnewchar = chr(newchar)
    encoded += newnewchar

print(repr(encoded))

打印出来:

'yp\x8b}z_\x88z\x91}o'

我只期待英文字母。知道什么可能是错的吗?

2 个答案:

答案 0 :(得分:2)

试用PyCharm,学会使用调试器。在其中运行代码很容易发现问题:

enter image description here

(突出显示的行是代码当前所在的位置,因此newchar == 121 == 72 + 75 - 26

即使没有PyCharm,我们的教训是,当您需要在代码中找出问题时,找到一种方法来查看每个阶段的值以测试您的假设。最简单的方法是在任何地方插入print(...)

答案 1 :(得分:1)

更加pythonic的方式是使用列表推导;

plaintext = 'THISISAPLAINTEXT'
key = 'SPAMEGGS'
count = int(len(plaintext)/len(key))+1

stretchedkey = [ord(c) for c in key*count]

# Encryption
plainnum = [ord(c) for c in plaintext]
ciphernum = [a+b-65 for a, b in zip(plainnum, stretchedkey)]
ciphertext = ''.join([chr(c) if c <= 90 else chr(c-26) for c in ciphernum])

# Decryption
ciphernum = [ord(c) for c in ciphertext]
decryptnum = [a-b+65 for a, b in zip(ciphernum, stretchedkey)]
decrypt = ''.join([chr(c) if c >= 65 else chr(c+26) for c in decryptnum])

显示IPython中的步骤;

In [1]: plaintext = 'THISISAPLAINTEXT'

In [2]: key = 'SPAMEGGS'

In [3]: count = int(len(plaintext)/len(key))+1

In [4]: stretchedkey = [ord(c) for c in key*count]

In [5]: plainnum = [ord(c) for c in plaintext]

In [6]: plainnum
Out[6]: [84, 72, 73, 83, 73, 83, 65, 80, 76, 65, 73, 78, 84, 69, 88, 84]

In [7]: ciphernum = [a+b-65 for a, b in zip(plainnum, stretchedkey)]

In [8]: ciphernum
Out[8]: [102, 87, 73, 95, 77, 89, 71, 98, 94, 80, 73, 90, 88, 75, 94, 102]

In [9]: ciphertext = ''.join([chr(c) if c <= 90 else chr(c-26) for c in ciphernum])

In [10]: ciphertext
Out[10]: 'LWIEMYGHDPIZXKDL'

In [11]: ciphernum = [ord(c) for c in ciphertext]

In [12]: decryptnum = [a-b+65 for a, b in zip(ciphernum, stretchedkey)]

In [13]: decryptnum
Out[13]: [58, 72, 73, 57, 73, 83, 65, 54, 50, 65, 73, 78, 84, 69, 62, 58]

In [14]: decrypt = ''.join([chr(c) if c >= 65 else chr(c+26) for c in decryptnum])

In [15]: decrypt
Out[15]: 'THISISAPLAINTEXT'