1本关任务:使用凯撒密码加密和解密英文文件。具体要求如下:
(1)接收一个字符串为参数,如果参数值为加密
,要求用户输入一个要加密的文件名
,再输入一个单词做为密钥发生器
,用于计算偏移量,对文件中的内容进行加密并输出;
(2)如果参数值为解密
,要求用户输入一个要解密的文件名
,再输入一个单词做为匹配词
,用于破解偏移量,输出解密后的文本
;
(3)若为其他输入,输出输入错误
。
代码如下:
import string
def judge(txt):
"""接收一个字符串为参数,如果参数值为“加密”,要求用户输入一个要加密的文件名,
再输入一个单词做为密钥发生器,用于计算偏移量,对文件中的内容进行加密并输出。
如果参数值为“解密”,要求用户输入一个要解密的文件名,再输入一个单词做为匹配词,
用于破解偏移量,输出解密后的文本。若为其他输入,输出'输入错误'。"""
###############################Begin#####################################
if txt == '加密':
file = input()
key_word = input()
print(caesar_cipher(read_txt(file), cal_offset(key_word)))
elif txt == '解密':
file = input()
key_text = input()
print(caesar_decrypt(read_txt(file), find_offset(key_text, read_txt(file))))
else:
print('输入错误')
################################End######################################
def read_txt(file):
"""接收文件名为参数,读取文件中的内容为一个字符串,返回这个字符串。"""
with open(file, 'r') as temp:
return temp.read()
def caesar_cipher(text, offset):
"""接收一个字符串为参数,采用字母表和数字中后面第offset个字符代替当前字符的方法
对字符串中的字母和数字进行替换,实现加密效果,返回值为加密的字符串。
例如:2019 abc 替换为5342 def """
###############################Begin#####################################
lower = string.ascii_lowercase # 小写字母
upper = string.ascii_uppercase # 大写字母
digit = string.digits # 数字
before = string.ascii_letters + digit
after = lower[offset:] + lower[:offset] + upper[offset:] + upper[:offset] + digit[offset:] + digit[:offset]
table = ''.maketrans(before, after)
caesar_cipher = text.translate(table)
return caesar_cipher
################################End######################################
def caesar_decrypt(text, offset):
"""接收一个加密的字符串text和一个整数offset为参数,采用字母表和数字中前面第offset个字符
代替当前字符的方法对字符串中的字母和数字进行替换,实现解密效果,返回值为解密的字符串。"""
###############################Begin#####################################
lower = string.ascii_lowercase # 小写字母
upper = string.ascii_uppercase # 大写字母
digit = string.digits # 数字
before = string.ascii_letters + digit
after = lower[offset:] + lower[:offset] + upper[offset:] + upper[:offset] + digit[offset:] + digit[:offset]
table = ''.maketrans(after, before)
decrypt_text = text.translate(table)
return decrypt_text
################################End######################################
def cal_offset(key_word):
"""接收一个单词为参数,计算这个单词的每个字母的ASCII值的和,
再对9取模,结果作为偏移量offset,返回这个偏移量。"""
###############################Begin#####################################
s = 0
for i in key_word:
s = s + ord(i)
offset = s % 9
return offset
################################End######################################
def find_offset(key_text, ciphertext):
"""接收一个明文单词和一个加密字符串为参数,尝试用[0,8]之间的数为偏移量进行解密。
若解密结果中包含这个明文单词,说明当前正在尝试的偏移量就是加密时所用偏移量,返回
这个整数偏移量。
"""
###############################Begin#####################################
offset = 0
for i in range(0,9):
if key_text in caesar_decrypt(ciphertext, i):
offset = i
return offset
################################End######################################
if __name__ == '__main__':
task = input()
judge(task)
(将带入参数的函数的返回值继续作为参数带入函数来实现编程任务)
2.这次的代码可能看着稍微复杂一点,函数虽然多,但还是通过定义,调用函数来实现目标功能