我一直收到索引错误:
User_input is 0
Key is 0
Traceback (most recent call last):
File "C:\Users\Theo_2\Google Drive\Computer science\Encryption and decryption work\Cipher 2\Cipher 2.5.0 alpha1.py", line 62, in <module>
Test_algorithm(5)
File "C:\Users\Theo_2\Google Drive\Computer science\Encryption and decryption work\Cipher 2\Cipher 2.5.0 alpha1.py", line 49, in Test_algorithm
Encrypt(User_input)
File "C:\Users\Theo_2\Google Drive\Computer science\Encryption and decryption work\Cipher 2\Cipher 2.5.0 alpha1.py", line 21, in Encrypt
ref_for_output = Master_Key.index(User_input[Count]) + Master_Key.index(Key[Count])
IndexError: string index out of range
基本上下面的代码是我写的一些内容的重写,用于使用关键字进行加密和解密。这个版本还没有完成,我的所有函数都已定义,包括一个测试每个可能的值,但我还没有启动任何接口。 无论如何,我的代码如下:
import time
Master_Key = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#£$%&'()*+,-./:;?@[\\]^_`{|}~\t\n\r\x0b\x0c"
global Output
Output = ""
global Key
Key = ""
def Compatibility_check(Key):
while Key == "":
print("Your key cannot be blank")
Key = input("Please input a new key: ")
while len(Key) > len(User_input):
Key = Key[:-1]
while len(Key) < len(User_input):
Key += (Key[Temp])
Temp += 1
def Encrypt(User_input):
Count = 0
Output = ""
while Count <= len(User_input):\
ref_for_output = Master_Key.index(User_input[Count]) + Master_Key.index(Key[Count])
if ref_for_output > len(Master_Key):
ref_for_output -= len(Master_Key)
Output += Master_Key[ref_for_output]
Count += 1
print(Output)
def Decrypt(User_input):
Count = 0
Output = ""
while Count <= len(User_input):
ref_for_output = Master_Key.index(User_input[Count]) - Master_Key.index(Key[Count])
if ref_for_output < 0:
ref_for_output += len(Master_Key)
Count += 1
Output += Master_Key[ref_for_output]
def Test_algorithm(Null):
fail, Input_Counter = False, 0
while Input_Counter <= len(Master_Key):
User_input = Master_Key[Input_Counter]
print("User_input is " + User_input)
Key_Counter = 0
Input_Counter += 1
while fail == False:
while Key_Counter < len(Master_Key):
Key = Master_Key[Key_Counter]
print("Key is " + Key)
Encrypt(User_input)
print("The encrypted value is " + Output)
Decrypt(Output)
print("The decrypted value is " + Output)
if Output == User_input:
print("The encryption and decryption of " + str(User_input) + " with the key " + str(Key_Counter) + " results in " + Output)
print("pass")
else:
print("fail")
print("The encryption and decryption of " + str(User_input) + " with the key " + str(Key_Counter) + " results in " + Output)
fail = True
Key_Counter += 1
Test_algorithm(Nothing)
##Key = "abcdefghijklmnop"
##User_input = "12345"
##Compatibility_check(Key)
##Encrypt(User_input)
##print(Output)
这是对旧脚本的改进,虽然有效但可以真正改进。我重写它的原因是我想将加密值输出到文件,然后根据用户请求重新读取和解密它们。 我希望你能帮忙 - 谢谢。
答案 0 :(得分:0)
看起来变量User_input是字符串&#34; 0&#34;因此当Count为1时会失败,因为索引从0开始,而User_input [1]是字符串的第二个字母。
你可能想从改变这个开始:
while Count <= len(User_input):
到此:
while Count < len(User_input):