蟒蛇的蛮力

时间:2013-09-17 11:46:07

标签: python

我正在尝试循环解密的消息10次,但是我得到的结果却截然不同,我不知道为什么。以下是我的代码。我使用相同的代码进行加密和解密。我只需要更改newchar = newchar-shfit。使用相同的代码进行循环会得到非常不同的结果。

  num1=0
  shift=0

  print("Brute force")

  question=input(print("Please enter something to decrypt: "))
  decryptedword = ""
  while num1<10 and shift <10 :


      for character in question:
          newchar = ord(character)
          newchar = newchar - shift
      if newchar < 32:
         newchar = newchar + 95
      elif newchar > 126:
         newchar = newchar - 95
      decryptedword = decryptedword + chr(newchar)


      print(num1,"decrypted word: ",decryptedword)
      num1=num1+1
      shift=shift+1

例如,如果在输入中键入asdasd,我会得到:

1个解密词:a

2解密字:ar

3解密词:arb

4解密词:arb ^

5解密字:arb ^ o

6解密词:arb ^ o _

好的,示例输出应该如何,如果我输入dvg,我应该得到:

1个解密词:fxi

2个解密词:asd

3解密词:ewh

依旧......

2 个答案:

答案 0 :(得分:2)

您每次循环迭代都会增加shift值,因此每次迭代都会改变您的密钥。而且由于每次迭代都会递增密钥(shift),因此每次迭代时解密结果也会不同。

如果删除此行shift=shift+1,则解密的消息应与每次迭代相同 (编辑方式3:我不知道如何'通过'文本,但上面的行应该被忽略,因为我误解了作者的问题。)

编辑:另外一点,你的缩进似乎是错误的。 if ; elif语句缩进,好像它们不是循环的一部分,这也会导致意外行为 EDIT2:此外decryptedword = ""应该在循环内部,因此每次迭代都会重置。

   num1=0
   shift=0


  print("Brute force")

  question=input(print("Please enter something to decrypt: "))
  while num1<10 and shift <10 :
      decryptedword = ""

      for character in question:
          newchar = ord(character)
          newchar = newchar - shift
          if newchar < 32:
             newchar = newchar + 95
          elif newchar > 126:
             newchar = newchar - 95
          decryptedword = decryptedword + chr(newchar)

      print(num1,"decrypted word: ",decryptedword)
      num1=num1+1
      shift=shift+1

答案 1 :(得分:2)

你的缩进是错误的 - if语句需要在for循环中

print("Brute force")

question=input(print("Please enter something to decrypt: "))
decryptedword = ""
while num1 < 10 and shift < 10:

for character in question:
    newchar = ord(character)
    newchar = newchar - shift
    if newchar < ord(' '):
        newchar = newchar + 95
    elif newchar > ord('~'):
        newchar = newchar - 95
    decryptedword = decryptedword + chr(newchar)


print(num1, "decrypted word: ", decryptedword)
num1 = num1 + 1
shift = shift + 1