文件加密/解密程序

帮同学写的一个有关文件操作的程序

要求如下

在这里插入图片描述

代码如下
# -*- coding: utf-8 -*-
"""
@author
@date
"""
import os

def 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, or x)? ")
    while(True):
        if inputstr == "e":
            keystr = input("What positive integer key would you like to use for encryption? ")
            while not 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? ")
            while not 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:")
            while not 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!")
            break
        else:
            inputstr = input("Sorry, that’s an invalid choice. Please enter only e, d, or x:")
    
""" Get the offset for a char in the sentence """
def getOffset(argv):    
    seq = "aA0bB1cC2dD3eE4fF5gG6hH7iI8jJ9kK lL,mM.nN?oO/pP;qQ:rR'sS\"tT!uU@vV$wW8xX&yY-zZ=" # This sequence is used to decrypte
    return seq.find(argv);

""" Get the char used to replace the original char"""
def getCypher(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  """
def encryptString(key,argv):
    cyphertext = "" # Record the secret message
    offset = getOffset(argv[0]) # Record the offset
    if offset != -1:
        cyphertext += getCypher(key+offset) 
    else:
        cyphertext += argv[0] 
    """" Encrypte the string(1~n) """
    for i in range(1,len(argv)):
        position = getOffset(argv[i]) # Record the position of the current char
        if 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  """
def decryptString(key, argv):
    message = "" # Record the secret message
    offset = getOffset(argv[0]) # Record the offset
    if offset != -1:
        message += getCypher(offset-key) 
    else:
        message += argv[0] 
    """" Decrypte the string(1~n) """
    for i in range(1,len(argv)):
        position = getOffset(argv[i]) # Record the position of the current char
        if 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"""
def checkFile(file):
    if os.path.exists(file):
        return True
    else:
        return False

""" Read file"""
def readFile(file):
    sentences = [] # Record the sentences in a file
    with open(file, "r") as f:
        sentences = f.readlines()
    return sentences 

""" Save file"""
def saveFile(file, content):
    with open(file, "w") as f:
        f.write(content)
    return file

""" Encrypte the file"""
def encryptFile(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"""
def decryptFile(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()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值