不解密我加密的内容

时间:2015-06-06 14:15:38

标签: python encryption

我的解密算法存在问题。它向文本文件输出一个重复的巨大列表(((((和其他东西。我的代码有什么问题,我该如何修复它?我认为它与最后一个函数有关)解密过程。但我不确定。

    import sys
    import os.path
    def convertToNum(ch):
        alpha ='''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!@#$%^&()-_=+[]{}\\|;:\'",./<>?\n\t '''
        index = alpha.find(ch)
    return index

def Matrix(text):
    evenChars = []
    oddChars = [] 
    index = 0

    for ch in text:        
        if index % 2 == 0:
        #this is an even character
            evenChars.append(convertToNum(ch))
        else: #this is an odd character
            oddChars.append(convertToNum(ch))

     index += 1
masterList = []
    if (evenChars >(oddChars)):
        oddChars.append(convertToNum(" "))    
    for i in range(len(evenChars)):
        masterList.append([evenChars[i],oddChars[i]])

    return masterList

def getMatrices(text):
    print("A list of integers acts as a key. Each value is stored in a,b,c,d. Please enter the values for: ")
    a = int(input("\nA :"))
    b = int(input("B :"))
    c = int(input("C :"))
    d = int(input("D :"))

    if (a*d) - (c*b) == 1:
        print("Valid Key\n")
    elif (a*d) - (c*b) ==-1:
        print("Valid Key\n")
    else:
        print("Invalid Key")
        sys.exit()

    indList = Matrix(text)
    encryptList = []
    for nestList in indList:
        x = nestList[0]
        y = nestList[1]
        encryptList.append(x*a + y*c) 
        encryptList.append(x*b + y*d)
    return encryptList

def backtoText(text):
    print("A list of integers acts as a key. Each value is stored in a,b,c,d. If you have already entered a key to encrypt, please use the same key. Please enter the values for: ")
    a = int(input("\nA :"))
    b = int(input("B :"))
    c = int(input("C :"))
    d = int(input("D :"))

    if (a*d) - (c*b) == 1:
        print("Valid Key\n")
    elif (a*d) - (c*b) ==-1:
        print("Valid Key\n")
    else:
        print("Invalid Key") 
        sys.exit()

    keyA = ((a*d) - (c*b)) * (d)
    keyB = ((a*d) - (c*b)) * (-b)
    keyC = ((a*d) - (c*b)) * (-c)
    keyD = ((a*d) - (c*b)) * (a)

    print(keyA,keyB,keyC,keyD)

    evenNums=[]
    oddNums=[]
    index = 0

    for ch in text:        #ch takes the place of the next characer in plain text
        if index % 2 == 0:
            evenNums.append(ch)
         else:
            oddNums.append(ch)

        index += 1    

    decrypted= []
    if (evenNums >(oddNums)):
         oddNums.append(" ")    
    for i in range(len(evenNums)):
         decrypted.append([evenNums[i],oddNums[i]])    

    indList = decrypted
    decryptList = []
    for nestList in indList:
        x = nestList[0]
        y = nestList[1]
        decryptList.append(x*keyA + y*keyC) 
        decryptList.append(x*keyB + y*keyD)
    return decryptList

def outPutString(text):
    alpha = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!@#$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t ''' 
    finalString =''
    text = backtoText(text)
    for ch in text:
        finalString += alpha[ch]
    return finalString

def main():
    print("What would you like to do?: ")
    answer = input("1) Encrypt File\n2) Decrypt File\n\n")
    if answer == '1':
        fileName = input("Please enter a filename to encrypt : ")
        if not os.path.isfile(fileName):
            print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
             sys.exit()

        plaintext_file = open(fileName)
        text = ""
        for line in plaintext_file.readlines():
             text += line + "\n"

        plaintext_file.close()
        name =input("Please enter the file name that you want to save the encrypted file as : ")
        if os.path.isfile(name) == False:
            matrices = getMatrices(text)
            for value in matrices:
                encrypted_file.write(str(value) + "\n")
            encrypted_file.close()
            encrypted_file.write(str(getMatrices(text)))
            encrypted_file.close()

        elif os.path.isfile(name) == True:
            answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
            if answer2 == 'y':
                encrypted_file = open(name,'w')
                encrypted_file.write(str(getMatrices(text)))
                encrypted_file.close()

            elif answer == 'n':
                print("Thank you for wasting time :D \n\n") 
                sys.exit()
            else:
                print("Invalid response. It's not hard to put y or n.\n\n") 
                sys.exit()

    elif answer == '2':
        fileName = input("Please enter a filename to decrypt : ")
        if not os.path.isfile(fileName):
            print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
            sys.exit()

        Encrypted_file = open(fileName)
        text = []
        for line in Encrypted_file.readlines():
            text.append(line)

        Encrypted_file.close()
        name = input("Please enter the file name that you want to save the decrypted text saved as : ")
        if os.path.isfile(name) == False:
            Decrypted_file = open(name,'w')
            Decrypted_file.write(str(outPutString(text)))
            Decrypted_file.close()                    

        elif os.path.isfile(name) == True:           
            answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
            if answer2 == 'y':
                Decrypted_file = open(name,'w')
                Decrypted_file.write(str(outPutString(text)))
                Decrypted_file.close()                        
            elif answer == 'n':
                print("Thank you for wasting time :D \n\n") 
                sys.exit()
            else:
                print("Invalid response. It's not hard to put y or n.\n\n") 
                sys.exit()

    else:
        print("Invalid Entry. The program will terminate")
        sys.exit()
 main()

1 个答案:

答案 0 :(得分:1)

这很有趣!

<{1>} def convertToNum(ch): alpha中的alpha不等于def outPutString(text):中的##(缺少*)导致(在我的情况下)标签而不是空格和?出现在我解密的字符串的末尾。我建议使用全局变量来防止将来发生这种情况。

您的加密算法运行良好,无需任何调整。在解密阶段有一些不兼容的变量类型,但我设法让一切工作,并包含工作代码(我的评论标有if (evenNum>(oddNum)))我希望这有帮助。

编辑:正如Eric在评论中指出的那样,if (len(evenNum)>len(oddNum))可能没有做你想做的事情。根据{{​​3}}:

  

可以将序列对象与具有相同序列类型的其他对象进行比较。比较使用词典排序:首先比较前两个项目,如果它们不同,则确定比较的结果;如果它们相等,则比较接下来的两个项目,依此类推,直到任一序列用完为止。

假设您要比较两个数组的长度以确保它们相等。如果是这种情况,那么您可能希望使用import sys import os.path def convertToNum(ch): alpha ='''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!@#$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t ''' #you forgot your asterix index = alpha.find(ch) return index def Matrix(text): evenChars = [] oddChars = [] index = 0 for ch in text: if index % 2 == 0: #this is an even character evenChars.append(convertToNum(ch)) else: #this is an odd character oddChars.append(convertToNum(ch)) index += 1 masterList = [] if (len(evenChars) >len(oddChars)): ## comparing lengths instead of contents oddChars.append(convertToNum(" ")) for i in range(len(evenChars)): masterList.append([evenChars[i],oddChars[i]]) return masterList def getMatrices(text): print("A list of integers acts as a key. Each value is stored in a,b,c,d. Please enter the values for: ") a = int(input("\nA :")) b = int(input("B :")) c = int(input("C :")) d = int(input("D :")) if (a*d) - (c*b) == 1: print("Valid Key\n") elif (a*d) - (c*b) ==-1: print("Valid Key\n") else: print("Invalid Key") sys.exit() indList = Matrix(text) encryptList = [] for nestList in indList: x = nestList[0] y = nestList[1] encryptList.append(x*a + y*c) encryptList.append(x*b + y*d) return encryptList def backtoText(text): print("A list of integers acts as a key. Each value is stored in a,b,c,d. If you have already entered a key to encrypt, please use the same key. Please enter the values for: ") a = int(input("\nA :")) b = int(input("B :")) c = int(input("C :")) d = int(input("D :")) if (a*d) - (c*b) == 1: print("Valid Key\n") elif (a*d) - (c*b) ==-1: print("Valid Key\n") else: print("Invalid Key") sys.exit() keyA = ((a*d) - (c*b)) * (d) keyB = ((a*d) - (c*b)) * (-b) keyC = ((a*d) - (c*b)) * (-c) keyD = ((a*d) - (c*b)) * (a) print(keyA,keyB,keyC,keyD) evenNums=[] oddNums=[] index = 0 newText = text[0].strip('[ ]') ## these two lines convert the string to an array textArray = newText.split(',') for ch in textArray: ## changed text to textArray(see above) #ch takes the place of the next characer in plain text if index % 2 == 0: evenNums.append(int(ch)) ## converting string number to int for later operations else: oddNums.append(int(ch)) index += 1 decrypted= [] if (len(evenNums) >len(oddNums)): ## comparing lengths instead of arrays oddNums.append(" ") for i in range(len(evenNums)): decrypted.append([evenNums[i],oddNums[i]]) indList = decrypted decryptList = [] for nestList in indList: x = nestList[0] y = nestList[1] decryptList.append(x*keyA + y*keyC) decryptList.append(x*keyB + y*keyD) return decryptList def outPutString(text): alpha = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!@#$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t ''' finalString ='' text = backtoText(text) for ch in text: finalString += alpha[ch] print(finalString) return finalString def main(): print("What would you like to do?: ") answer = input("1) Encrypt File\n2) Decrypt File\n\n") if answer == '1': fileName = input("Please enter a filename to encrypt : ") if not os.path.isfile(fileName): print("Invalid Entry. Computer will self destruct in 10 seconds\n\n") sys.exit() plaintext_file = open(fileName) text = "" for line in plaintext_file.readlines(): text += line ##+ "\n" ##you don't need to add a new line as '\n' is already included at the end of every line. plaintext_file.close() name =input("Please enter the file name that you want to save the encrypted file as : ") if os.path.isfile(name) == False: ##matrices = getMatrices(text) ##for value in matrices: ##encrypted_file.write(str(value) + "\n") ##encrypted_file.close() ## I added the line below(and removed lines above) to be consistent with your later usage encrypted_file = open(name,'w') encrypted_file.write(str(getMatrices(text))) encrypted_file.close() elif os.path.isfile(name) == True: answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ") if answer2 == 'y': encrypted_file = open(name,'w') encrypted_file.write(str(getMatrices(text))) encrypted_file.close() elif answer == 'n': print("Thank you for wasting time :D \n\n") sys.exit() else: print("Invalid response. It's not hard to put y or n.\n\n") sys.exit() elif answer == '2': fileName = input("Please enter a filename to decrypt : ") if not os.path.isfile(fileName): print("Invalid Entry. Computer will self destruct in 10 seconds\n\n") sys.exit() Encrypted_file = open(fileName) text = [] for line in Encrypted_file.readlines(): text.append(line) Encrypted_file.close() name = input("Please enter the file name that you want to save the decrypted text saved as : ") if os.path.isfile(name) == False: Decrypted_file = open(name,'w') Decrypted_file.write(str(outPutString(text))) Decrypted_file.close() elif os.path.isfile(name) == True: answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ") if answer2 == 'y': Decrypted_file = open(name,'w') Decrypted_file.write(str(outPutString(text))) Decrypted_file.close() elif answer == 'n': print("Thank you for wasting time :D \n\n") sys.exit() else: print("Invalid response. It's not hard to put y or n.\n\n") sys.exit() else: print("Invalid Entry. The program will terminate") sys.exit() main()

#include <stdlib.h>
#include <stdio.h>
#include <mruby.h>
#include <mruby/compile.h>

int main(void)
{
  mrb_state *mrb = mrb_open();
  if (!mrb) { /* handle error */ }
  puts("Executing Ruby code from C!");
  mrb_load_string(mrb, "p 'hello world!'");
  mrb_close(mrb);
  return 0;
}