python加密和解密查询

时间:2015-02-20 02:05:04

标签: python encryption

所以我在初学python类。我也是中级C ++,但这个任务让我陷入了循环。 以下是两部分: 加密:

    # encrypt.py - ENCODE MESSAGE AND WRITE TO FILE
#
# initialize a cipher list to store the numeric value of each character
# input a string of text to encrypt
#
# for each character in the string:
# convert the character to its unicode value
# encode the unicode value into an integer with an encryption formula
# convert the encoded integer to a string
# append the encoded string to the cipher list
#
# for debugging purposes, print the cipher list - make sure data is correct
#
# open an output file to store the encrypted message
# write (print) the cipher list to the file
# close the file
def main():
    cipher = []
    #initialize string message
    message=input('Please enter your message for encryption: ')

    #loops through string message and encrypts 
    for ch in message:
        x = ord(ch)
        x = (2*x)-3
        x = chr(x)
        cipher.append(x)
    #Print cipher from prompt
    print("Your code message is: ",cipher)
    #open file for writing
    outFile = open("Encryptedmessage.txt","w")
    print(cipher, file=outFile)
main()

This program works fine. The decryption program is as follows:

    # decrypt.py - DECODE MESSAGE FROM FILE AND DISPLAY
#
# initialize a message list to contain the decoded message
# open the input file containing the encrypted message
# read the line containing the message from the file into a string
# split the string into a cipher list of individual strings
#
# for each string in the cipher list:
# convert the string to an integer
# decode the integer into its unicode value using the decryption formula
# convert the unicode value to its corresponding character
# append the character to the message list
#
# print the message list
# close the file

def main():
    deCipher=[]

    infile = open("Encryptedmessage.txt","r")
    with open('Encryptedmessage.txt') as f:
        lines=f.readlines()
    secMess=str.split

    for ch in infile:
        y=ord(ch)
        y=(y//2)+3
        y=chr(y)
        deCipher.append(y)
        print(deCipher)



main()

当我尝试运行decrypt.py时出现以下错误:

>>> 
Traceback (most recent call last):
  File "G:/Python34/decrypt.py", line 34, in <module>
    main()
  File "G:/Python34/decrypt.py", line 26, in main
    y=ord(ch)
TypeError: ord() expected a character, but string of length 59 found
>>> 

我一直试图在这方面找到一些方向无济于事。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

你的加密有一个错误;将最后一行更改为:

print(''.join(cipher), file=outFile)

然后,这将用于解密:

def main():
    deCipher=[]

    infile = open("Encryptedmessage.txt","r")
    with open('Encryptedmessage.txt') as f:
        lines=f.readlines()
    secMess=lines[0].rstrip()

    for ch in secMess:
        y=ord(ch)
        y=(y+3)//2
        y=chr(y)
        deCipher.append(y)
    print(''.join(deCipher))
main()

首先,你有一个错误的解密公式。另一方面,你正在迭代一个错误的东西(infile),而你的secMess也不是你想象的那样。