2013-11-02 52 views
0

我一直在研究一個加密程序,它只是將一個字符串加密爲十進制值,並將編寫另一個程序來解密它。至於現在是做什麼用的十進制值,但是當我嘗試進行XOR我使用的是二進制文件進行加密則返回錯誤加密程序不工作 - TypeError:字符串索引必須是整數,而不是str

Traceback (most recent call last): 
    File "./enc.py", line 53, in <module> 
    encrypt() 
    File "./enc.py", line 35, in encrypt 
    val1 = text2[i] + decryptionKey[j] 
    TypeError: string indices must be integers, not str 

下面是代碼

#!/usr/bin/env python2 
    import sys 
    def encrypt(): 
     text1 = raw_input("Please input your information to encrypt: ") 
     text2 = [] 
     #Convert text1 into binary (text2) 
     for char in text1: 
     text2.append(bin(ord(char))[2:]) 
     text2 = ''.join(text2) 

     key = raw_input("Please input your key for decryption: ") 
     decryptionKey = [] 
     #Convert key into binary (decryptionKey) 
     for char in key: 
     decryptionKey.append(bin(ord(char))[2:]) 
     decryptionKey = ''.join(decryptionKey) 

     #Verification String 
     print "The text is '%s'" %text1 
     print "The key is '%s'" %key 
     userInput1 = raw_input("Is this information ok? y/n ") 
     if userInput1 == 'y': 
     print "I am encrypting your data, please hold on." 
     elif userInput1 == 'n': 
     print "Cancelled your operation." 
     else: 
     print "I didn't understand that. Please type y or n (I do not accept yes or no as an answer, and make sure you type it in as lowercase. We should be able to fix this bug soon.)" 

     finalString = [] 

     if userInput1 == 'y': 
     for i in text2: 
      j = 0 
      k = 0 
      val1 = text2[i] + decryptionKey[j] 
      if val1 == 0: 
      finalString[k] = 0 
      elif val1 == 1: 
      finalString[k] = 1 
      elif val1 == 2: 
      finalString[k] = 0 
      j += 1 
      k += 1 
     print finalString 






encrypt() 

如果它會更容易,你還可以查看源@https://github.com/ryan516/XOREncrypt/blob/master/enc.py

回答

1
for i in text2: 

這不會給列表的索引,但字符串作爲字符串的實際字符。您可能需要使用enumerate

for i, char in enumerate(text2): 

例如,

text2 = "Welcome" 
for i in text2: 
    print i, 

將打印

W e l c o m e 

text2 = "Welcome" 
for i, char in enumerate(text2): 
    print i, char 

會給

0 W 
1 e 
2 l 
3 c 
4 o 
5 m 
6 e 
+0

等待,這是否將該數組視爲Char數組?我希望這是一個十進制數組...對於成爲一個Python Noob感到抱歉,但是解釋器是如何看待它的? –

+0

@RyanSmith如果對字符串使用normal循環,它將作爲char數組迭代。由於python中沒有char數據類型,因此每一個char都被視爲python中的字符串。 – thefourtheye

+0

但這是一個字符/字符串數組?我很困惑:(。我曾希望它是一個二進制或十進制數字操作數組,出錯了嗎? –

相關問題