凯撒密码实现

凯撒密码实现
可以加密中文

在这里插入代码片
# 只能是数字密码,字母密码会出错
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)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值