2014-12-24 3 views
0

키를 사용하여 암호화하고 해독하는 알고리즘을 작성 중입니다. 또는 오히려 가지고,이 내 코드를 구성하는 재 작성의 이상입니다. 어쨌든 방금 텍스트 기반 인터페이스를 만들기 시작했습니다. Tkinter는 나중에 나옵니다.이 색인은 어디에서 오는가?

12345와 같이 설정 한 키를 인덱싱 할 때 "IndexError : string index of range"가 표시됩니다. 나는 이것이 무엇을 의미하는지 안다. 그러나 전체 문자열이 루프 내에서 인덱싱되고 있다는 것도 알고 있습니다. 0에서 시작하여 오류를 가져옵니다. 필자는 테스트를 시도해 보았습니다. print (Key [0]) 그러나 파이썬은 여전히 ​​오류를 던집니다. 이유는 모르겠다. 그것은 있지만,

는 특히 내 문제는 Encrypt 기능에 생각 : 그것은 여기 참고 1.

Do you want to encrypt or decrypt? encrypt 
Input a string toencrypt- Hello123 
Input a key- 12345 
123451 
1234512 
12345123 
Key = 
Traceback (most recent call last): 
    File "C:\Users\Theo_2\Google Drive\Computer science\Encryption and decryption work\Cipher 2\Cipher 2.5.0 Beta .py", line 142, in <module> 
    User_text_interface(True) 
    File "C:\Users\Theo_2\Google Drive\Computer science\Encryption and decryption work\Cipher 2\Cipher 2.5.0 Beta .py", line 137, in User_text_interface 
    print(str(Encrypt(User_input))) 
    File "C:\Users\Theo_2\Google Drive\Computer science\Encryption and decryption work\Cipher 2\Cipher 2.5.0 Beta .py", line 27, in Encrypt 
    print(Key[0]) 
IndexError: string index out of range 

를 반환해야합니다 0 문자열 12345을 참조하는 것은 내 코드입니다 역시 Decrypt 일 수 있습니다.

>>> Key = '' 
>>> Key[0] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IndexError: string index out of range 

당신 때문이다 : 나는

import time, sys 
Master_Key = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#£$%&'()*+,-./:;[email protected][\\]^_`{|}~\t\n\r\x0b\x0c" 
global Output 
Output = "" 
global Key 
Key = "" 
##global User_input 
def Compatibility_check(Key, User_input): 
    Temp = 0 
    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 
     print(Key) 

def Encrypt(User_input): 
    ##Compatibility_check(Key) 
    Count = 0 
    global Output 
    Output = "" 
    while Count < len(User_input): 
     print(Key[0]) 
     print("Count = " + str(Count)) 
     print("Key count = " + str(Key[Count])) 
     print("Master_key.index") 
     print("Testing- Input indexer- " + str(Master_Key.index(User_input[Count]))) 
     print("Testing- Key indexer- " + str(Master_Key.index(Key[Count]))) 


     ref_for_output = Master_Key.index(User_input[Count]) + Master_Key.index(Key[Count]) 
     if ref_for_output >= len(Master_Key): ## As [] starts from zero 
      ref_for_output -= len(Master_Key) 
     Output += Master_Key[ref_for_output] 
     Count += 1 
    ##print("Output is " + Output) 
    return Output 

def Decrypt(User_input): 
    ##Compatibility_check(Key) 
    Count = 0 
    global Output 
    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) 
     Output += Master_Key[ref_for_output] 
     Count += 1 
    ##print("Output is " + Output) 
    return Output 

def Test_algorithm(Null): 
    Counter1 = 0 
    while Counter1 < (len(Master_Key)-1): ##If <= doesnt work use (len(Master_Key)-1) 
     Input, Counter2 = Master_Key[Counter1], 0 
     print("Input = " + Input) 
     Counter1 += 1 
     print("Loop 1") 
     if Counter1 == len(Master_Key): 
      print("The program works.") 
     while Counter2 < (len(Master_Key)-1): 
      global Key 
      Key = Master_Key[Counter2] 
      Encrypt(Input) 
      ##Temp = Output 
      Decrypt(Output) 
      print("Encryption and decryption of Input- " + str(Input) + " with the Key- " + str(Key) + " results in an output of " + str(Output)) 
      if Input == Output: 
       print("Pass") 
      else: 
       print("Fail") 
       sys.exit 
      Counter2 += 1 
      ##Counters are used here, it is simply easier to use a counter and a while loop when dealing with references from a for loop 

def User_text_interface(Repeat): 
    while Repeat == True: 
     ED = input("Do you want to encrypt or decrypt? ") 
     User_input = input("Input a string to" + str(ED) + "- ") 
     Key = input("Input a key- ") 
     Compatibility_check(Key, User_input) 
     if ED.lower() == "encrypt" or ED.lower() == "e": 
      print(str(Encrypt(User_input))) 
     elif ED.lower() == "decrypt" or ED.lower() == "d": 
      print(str(Decrypt(User_input))) 


User_text_interface(True) 
+0

예외의 전체 추적 *을 제공해야합니다. –

+0

아아아. 그냥 암호화 키 내부를 보았고 안에 있습니다. 비어있는 것 같습니다. 내 호환성 검사 기능에 문제가있을 수 있습니다. –

+0

완료했습니다. 죄송합니다. 이전에 잊어 버렸습니다 –

답변

2

귀하의 Key 변수가 빈 문자열 괜찮 았는데 암호화 및 암호 해독의 루프를 통해 모든 가치를 실행하고, 중간에 주석 물건을 무시하십시오 Key 변수를 변경하지 않습니다. 로컬 변수 만 변경하십시오. global 문은 기능에 을 넣어해야합니다

def Compatibility_check(Key, User_input): 
    global Key 
    Temp = 0 
    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 
     print(Key) 

하지만 기능 반환 새로운 값이 더 나은 것;

Key = Compatibility_check(Key, User_input) 
+0

네, 그게 방금 깨달은 것입니다. 당신의 도움을 주셔서 감사합니다. –

0

내 문제가 분명했다 끈다 : 당신은 return Key (기능 종료)이 그 반환 값을 할당 사용하십시오. 호환성 검사 기능을 작성하는 과정에있었습니다. 기본적으로 Key와 User_input이라는 두 개의 입력이 필요했습니다. 그래서 Key가 다양한 것을 확인하고 만나지 않으면 변경합니다. 불행히도 나는 'Key'와 동일한 이름을 가진 내부 변수 'Key'를 나중에 변경한다는 사실을 간과했다.

이것은 키가 입력보다 짧음을 의미하며 암호화 기능은 존재하지 않는 키의 문자를 참조하려고했습니다.

관련 문제