繁体   English   中英

Python中的Vigenere Cypher

[英]Vigenere Cypher in Python

我正在尝试用Python编写vigenere应用程序。 这是应用程序应运行的方式:

  1. 运行程序
  2. 输入“ 1”加密或“ 2”解密消息
  3. 输入您的密码
  4. 输入要加密/解密的输入纯文本文件
  5. 输入将存储现在加密/解密的文本的输出文件

密文密钥是一串字母数字chars ,然后将其转换为int ,该数字用于将纯文本旋转为密文。 例如: Aa旋转一个字母进行加密解密的权利或一个字母的左边。

几乎一切正常。 如果我输入英语纯文本文件,对其进行加密,然后使用相同的密钥对该文件解密,则输出文件应该与我开始使用的纯文本文件完全一样...并且除了换行符外。 一些原有的换行符已消失,而一些新的换行符也已投入使用。

我花了很长时间试图了解自己在做什么错。 我将不胜感激。 这是完整的代码:

# ask user if he/she wishes to encrypt or decrypt a message
pmode = 0
while True:
    try:
        pmode = int(input("Enter 1 to encrypt or 2 to decrypt a message: "))
        while pmode not in {1, 2}:
            int(input("Oops! Please enter 1 or 2: "))
            break
        break
    except (ValueError, NameError):
        print("Oops! That entry is not supported, try again...")

# ask user for a cypher keyword
key = input("Enter codeword: ")

# create list to store converted key
keylength = len(key)
realkey = [] * keylength

# convert "key" from string of chars to string of ints
for i in key:
    if i.isalpha():
        if i.isupper():
            realkey.append(ord(i) % ord('A') + 1)
        elif i.islower():
            realkey.append(ord(i) % ord('a') + 1)
    elif ord(i) >= 48 and ord(i) <=57:
        realkey.append(int(i))
    else:
        realkey.append(0)

# prompt user for input file and open it
infile_name = input("Enter input file name: ")
infile = open(infile_name, 'r')

# prompt user for output file and open it
outfiler_name = input("Enter output file name: ")
outfile = open(outfiler_name, "w")

# if on encryption mode, encrypt
if pmode == 1:
    # iterate over inmessage and rotate (within ASCII chars 32 - 126) using realkey
    indx = -1
    # loop over infile, encrypt and write to outfile
    while True:
        # temp variable to store current char
        char = infile.read(1)
        indx += 1
        # stop when EOF is reached
        if not char:
            break
        else:
            if ord(char) + realkey[indx % keylength] > 126:
                outfile.write(chr((ord(char) - 126 + realkey[indx % keylength])))
            else:
                outfile.write(chr((ord(char) + realkey[indx % keylength])))
else:
    # iterate over inmessage and rotate (within ASCII chars 32 - 126) using realkey
    indx = -1
    # loop over infile, encrypt and write to outfile
    while True:
        # temp variable to store current char
        char = infile.read(1)
        indx += 1
        # stop when EOF is reached
        if not char:
            break
        else:
            if ord(char) + realkey[indx % keylength] < 32:
                outfile.write(chr((ord(char) + 126 - realkey[indx % keylength])))
            else:
                outfile.write(chr((ord(char) - realkey[indx % keylength])))

# close files
infile.close()
outfile.close()

谢谢。

因为\\n (换行符)是ascii 10,所以请记住ord('\\ n')== 10

此时您有2种可能性

  1. ord(char) + realkey[indx % keylength] < 32:
    • 通常是正确的,除非ord(key_letter)-ord('a') >= 22
    • 如果它为true(例如'a'(real_key值为1 ),则10 + 126 + 1 = 137(或'\\x89'
    • 现在,当我们稍后尝试再次使用相同的key_letter对其进行解码时
      • ord('\\ x89')== 137
      • 因此我们的ord(char) + realkey[indx % keylength] < 32:的if语句为false
      • 我们将使用else规则将其解码为89 - 1 ,这肯定不会使我们回到10,因此这将字符串解码为错误
  2. 或不是,这种情况甚至更糟...

我想答案是您的算法在很多情况下都会崩溃...并且应该完全重构....我将为您提供一些重构的建议,这将有助于使其更易于测试

  • 在测试硬编码时,您的用户密钥key="Yellow55"
  • 同样,对您的字符串进行硬编码以进行加密和解密,请确保它具有一些较难的字符(例如换行符) my_string="Hello\\nTest\\t\\rString\\r\\n" ...真的,只使用string.printable作为应该包括所有ascii字母作为测试用例...
  • 使用函数...我对此压力还不够!!!

职能

def decrypt(string_to_decrypt,key):
    #do your stuff
def encrypt(string_to_encrypt,key):
    #do your stuff
  • 而不是while True: i+=1 ...您应该将for i,value in enumerate(my_list):

  • 打印出很多东西……我的意思是真的……打印出所有东西,这几乎总是使您的错误非常明显

    如果您无法出于某种原因打印所有内容,请至少使用调试器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM