defcaesar_encryption():"""
在密码学中,恺撒密码(英语:Caesar cipher),或称恺撒加密、恺撒变换、变换加密,是一种最简单且最广为人知的加密技术。
它是一种替换加密的技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。
例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推。
"""
flag =0while(flag ==0):try:print("please enter file path,For example D:/text.txt")
filepath =input("path:")
file1 =open(filepath,'r+', encoding='UTF-8')
a = file1.read()print(a)
alphabet ="a b c d e f g h i j k l m n o p q r s t u v w x y z"
a1 = alphabet.upper()
a2 = alphabet.split(' ')
a3 = a1.split(' ')
putlist =[]for i in a:if i in a2:
x =(a2.index(i)+3)%26
putlist.append(a2[x])elif i in a3:
x =(a3.index(i)+3)%26
putlist.append(a3[x])else:
putlist.append(i)
out =''.join(putlist)
file1.close()print("Please enter the ciphertext storage path,For example D:/text.txt")
filepath =input("path:")
file2 =open(filepath,'w+', encoding='UTF-8')
file2.write(out)print("加密成功,密文路径为:%s"%filepath)
flag =1except Exception:print("文件打开失败,请检查文件路径是否正确")
caesar_encryption()
凯撒解密
defcaesar_decrypt():
flag =0while(flag ==0):try:print("please enter ciphertext storage path path,For example D:/text.txt")
filepath =input("path:")
file1 =open(filepath,'r+', encoding='UTF-8')
key =int(input("key(Must be a number):"))
a = file1.read()print(a)
alphabet ="a b c d e f g h i j k l m n o p q r s t u v w x y z"
a1 = alphabet.upper()
a2 = alphabet.split(' ')
a3 = a1.split(' ')
putlist =[]for i in a:if i in a2:
x =(a2.index(i)+(26-key))%26
putlist.append(a2[x])elif i in a3:
x =(a3.index(i)+(26-key))%26
putlist.append(a3[x])else:
putlist.append(i)
out =''.join(putlist)
file1.close()print("Please enter the Decrypt file,For example D:/text.txt")
filepath =input("path:")
file2 =open(filepath,'w+', encoding='UTF-8')
file2.write(out)print("解密成功,密文路径为:%s"%filepath)
flag =1except Exception:print("文件打开失败,请检查文件路径是否正确")
caesar_decrypt()