凯撒密码实现
可以加密中文
在这里插入代码片
# 只能是数字密码,字母密码会出错
import GUIpy.PublicPy as ppy
def Encryption(plaintexts, passwds):
i = j = 0
ciphers = []
while i < len(plaintexts):
plaintext = int.from_bytes(plaintexts[i].encode("utf-8"), "big")
passwd = int.from_bytes(passwds[j].encode("utf-8"), "big")
if j == (len(passwds) - 1):
j = 0
if plaintext <= 127:
cipher = plaintext + passwd
if cipher > 127:
cipher = cipher - 127
x=chr(cipher)
else:
cipher = (plaintext ^ passwd).to_bytes(3, "big")
x = cipher.decode("utf-8")
ciphers.append(x)
i += 1
j += 1
return "".join(ciphers)
def Decryption(ciphers, passwds):
i = j = 0
plaintexts = []
while len(ciphers) > i:
cipher = int.from_bytes(ciphers[i].encode("utf-8"), "big")
passwd = int.from_bytes(passwds[j].encode("utf-8"), "big")
if j == (len(passwds) - 1):
j = 0
if cipher == 0:
N_plaintext = passwd
x = N_plaintext.to_bytes(3, "big").decode("utf-8")
elif cipher <= 127:
plaintext = cipher - passwd
if plaintext < 0:
plaintext = 127+plaintext
x = chr(plaintext)
else:
N_plaintext = ~(cipher ^ (~passwd))
x = N_plaintext.to_bytes(3, "big").decode("utf-8")
plaintexts.append(x)
i += 1
j += 1
return "".join(plaintexts)
def KEncode(filepath, passwd):
file = ppy.openfile(filepath)
return Encryption(file, passwd)
def KDecode(filepath, passwd):
file = ppy.openfile(filepath)
return Decryption(file, passwd)
if __name__ == '__main__':
password = "132457680953"
test=ppy.openfile('C:/Users/XXX/Desktop/test.txt')
#test = "1.“睡不着,在数羊的时候,突然有一只小羊站了出来对我说“请你用心一点,你已经数过我一次了。”"
#print("要加密的文本:\n", test)
miwen = Encryption(test, password)
#print(miwen.encode('utf-8'))
print("加密后的文本:\n", miwen)
mingwen = Decryption(miwen, password)
print("解密后的文本:\n", mingwen)