Search code examples
pythonencryptionxor

Encryption Program not working - TypeError: string indices must be integers, not str


I've been working on an encryption program which just encrypts a string into decimal values, and will write another program that will decrypt it. As of right now it is doing nothing with the decimal values, but when I try to XOR the binaries I'm using for encryption it returns the error

    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

Here is the code

    #!/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()

If it would be easier, you can also view the source @ https://github.com/ryan516/XOREncrypt/blob/master/enc.py


Solution

  • for i in text2:
    

    This will not give indices of the list, but the actual characters of the string as string. You may want to use enumerate

    for i, char in enumerate(text2):
    

    For example,

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

    will print

    W e l c o m e
    

    but

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

    will give

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