# -*- coding: utf-8 -*-"""
@author
@date
"""import os
defmain():print("Welcome to the Encryption/ Decryption Program")
inputstr =input("Would you like to (e)ncrypt a file, (d)ecrypt a file, or e(x)it (enter e, d, or x)? ")while(True):if inputstr =="e":
keystr =input("What positive integer key would you like to use for encryption? ")whilenot keystr.isdigit():
keystr =input("Sorry, that’s an invalid choice. Please enter a positive integer: ")
key =int(keystr)file=input("Enter the text-file name to encrypt:")if checkFile(file):
newfile =file[0:len(file)-3]+"zzz"
ctext = encryptFile(key,file)
saveFile(newfile,ctext)print("The file ‘"+file+"’ was successfully encrypted using a key of "+str(key)+" to the file '"+ newfile+"'")else:while(not checkFile(file)):file=input("Sorry the file ‘"+file+"’ does NOT exist -- please try again!\nEnter the text-file name to encrypt: ")
newfile =file[0:len(file)-3]+"zzz"
ctext = encryptFile(key,file)
saveFile(newfile,ctext)print("The file ‘"+file+"’ was successfully encrypted using a key of "+str(key)+" to the file '"+ newfile+"'")
inputstr =input("Would you like to (e)ncrypt a file, (d)ecrypt a file, or e(x)it (enter e, d, or x)? ")elif inputstr =="d":
keystr =input("What positive integer key would you like to use for decryption? ")whilenot keystr.isdigit():
keystr =input("Sorry, that’s an invalid choice. Please enter a positive integer: ")
key =int(keystr)file=input("Enter the text-file name to decrypt:")whilenot checkFile(file):file=input("Sorry the file ‘"+file+"’ does NOT exist -- please try again!\nEnter the text-file name to decrypt: ")
newfile =file[0:len(file)-3]+"txt"if checkFile(newfile):
choice =input("WARNING: The file "+"‘"+ newfile +" ’ already exists!\n Is it okay to wipe it out (y/n)? ")if choice =='y':
dtext = decryptFile(key,file)
saveFile(newfile,dtext)print("The file ‘"+file+"’ was successfully decrypted using a key of "+str(key)+" to the file '"+ newfile +"'")elif choice =='n':
output =input("Enter the file name that should be used (.txt extension will automatically be added): ")
output = output+".txt"
dtext = decryptFile(key,file)
saveFile(output, dtext)print("The file ‘"+file+"’ was successfully decrypted using a key of "+str(key)+" to the file '"+ output +"'")else:while(choice !='y'or choice !='n'):
choice =input("Sorry, that’s an invalid choice. Please enter only y or n: ")if choice =='y':
dtext = decryptFile(key,file)
saveFile(newfile, dtext)print("The file ‘"+file+"’ was successfully decrypted using a key of "+str(key)+" to the file '"+ newfile +"'")elif choice =='n':
output =input("Enter the file name that should be used (.txt extension will automatically be added): ")
output = output+".txt"
dtext = decryptFile(key,file)
saveFile(output, dtext)print("The file ‘"+file+"’ was successfully decrypted using a key of "+str(key)+" to the file '"+ output +"'")else:
dtext = decryptFile(key,file)
saveFile(newfile, dtext)print("The file ‘"+file+"’ was successfully decrypted using a key of "+str(key)+" to the file '"+ newfile +"'")
inputstr =input("Would you like to (e)ncrypt a file, (d)ecrypt a file, or e(x)it (enter e, d, or x)? ")elif inputstr =="x":print("Bye!")breakelse:
inputstr =input("Sorry, that’s an invalid choice. Please enter only e, d, or x:")""" Get the offset for a char in the sentence """defgetOffset(argv):
seq ="aA0bB1cC2dD3eE4fF5gG6hH7iI8jJ9kK lL,mM.nN?oO/pP;qQ:rR'sS\"tT!uU@vV$wW8xX&yY-zZ="# This sequence is used to decryptereturn seq.find(argv);""" Get the char used to replace the original char"""defgetCypher(key):
seq ="aA0bB1cC2dD3eE4fF5gG6hH7iI8jJ9kK lL,mM.nN?oO/pP;qQ:rR'sS\"tT!uU@vV$wW8xX&yY-zZ="# This sequence is used to decrypte if key >len(seq)-1:
key = key -len(seq)return seq[key];""" Encrypte the string """defencryptString(key,argv):
cyphertext =""# Record the secret message
offset = getOffset(argv[0])# Record the offsetif offset !=-1:
cyphertext += getCypher(key+offset)else:
cyphertext += argv[0]"""" Encrypte the string(1~n) """for i inrange(1,len(argv)):
position = getOffset(argv[i])# Record the position of the current charif position !=-1:
cnt =1
offset = getOffset(argv[i-1])while(offset ==-1):
cnt = cnt+1# Deal with chars not in the seq
offset = getOffset(argv[i-cnt])
cyphertext += getCypher(offset+position)else:
cyphertext += argv[i]return cyphertext
""" Decrypte the string """defdecryptString(key, argv):
message =""# Record the secret message
offset = getOffset(argv[0])# Record the offsetif offset !=-1:
message += getCypher(offset-key)else:
message += argv[0]"""" Decrypte the string(1~n) """for i inrange(1,len(argv)):
position = getOffset(argv[i])# Record the position of the current charif position !=-1:
cnt =1
offset = getOffset(message[i-1])while(offset ==-1):
cnt = cnt+1# Deal with chars not in the seq
offset = getOffset(message[i-cnt])
message += getCypher(position-offset)else:
message += argv[i]return message
""" Check if the file exists"""defcheckFile(file):if os.path.exists(file):returnTrueelse:returnFalse""" Read file"""defreadFile(file):
sentences =[]# Record the sentences in a filewithopen(file,"r")as f:
sentences = f.readlines()return sentences
""" Save file"""defsaveFile(file, content):withopen(file,"w")as f:
f.write(content)returnfile""" Encrypte the file"""defencryptFile(key,file):
lines = readFile(file)# Record the list to be encrypted
newlines =[]# Record the list encrypted
length =[]# Record the position of "\n"
text =""# Record the text to encrypted
newtext =""# Record the cyphertext""" Get text"""for line in lines:
length.append(len(line))
text += line.strip("\n")""" Encrypte """
newtext = encryptString(key, text)""" Get newlines """for l in length:
newlines.append(newtext[0:l-1]+"\n")
newtext = newtext[l-1:len(newtext)]
newtext =""for s in newlines:
newtext += s
return newtext
""" Decrypte the file"""defdecryptFile(key,file):
lines = readFile(file)# Record the list to be encrypted
newlines =[]# Record the list encrypted
length =[]# Record the position of "\n"
text =""# Record the text to encrypted
newtext =""# Record the cyphertext""" Get text"""for line in lines:
length.append(len(line))
text += line.strip("\n")""" Encrypte """
newtext = decryptString(key, text)""" Get newlines """for l in length:
newlines.append(newtext[0:l-1]+"\n")
newtext = newtext[l-1:len(newtext)]
newtext =""for s in newlines:
newtext += s
return newtext
if __name__ =='__main__':
main()
帮同学写的一个有关文件操作的程序要求如下代码如下# -*- coding: utf-8 -*-"""@author@date"""import osdef main(): print("Welcome to the Encryption/ Decryption Program") inputstr = input("Would you like to (e)ncrypt a file, (d)ecrypt a file, or e(x)it (enter e, d, o