python 移位加密

题目:

移位加密。随机生成密钥k,0<k<256,将原始文件的每个字节加k,超过256则减去256,得到该字节的密文。解密则减k,小于0则加256。

在ASCii编码层面前后简单移位变换,移位长度限定在0~255,如果需要可以自行更改。

为了增加移位加密的安全性,对每行的数据都随机生成一个移位长度

直接上代码:

(移位明文.txt :记录你要加密的数据,支持任何字符,支持换行记录

移位密钥.txt :记录生成的密钥

移位密文.txt : 记录加密后生成的密文)

import secrets
import os

def write_txt2(name, content):
    path = os.getcwd() + '\\' + name + '.txt'
    if os.path.exists(path):
        print(name + '文件存在,覆盖原文件')
    else:
        print(name + '文件不存在,创建文件')
    with open(path, 'w', encoding='utf8') as f:  # 写入新文件
        for i in content:
            f.write(i + '\n')
        f.close()

# 打开文件
def read_txt2(name):
    content = []
    # with open(os.getcwd()+"\\"+name+".txt","r",encoding='utf8') as f:
    with open(name, "r", encoding='utf8') as f:
        for i in f.readlines():
            # i = i.strip('\n')
            i = i.rstrip('\n')
            content.append(i)
    f.close()
    return content

# 随机生成密钥
def pro_secretkey2(plaintext):
    secretkey=[]
    for i in range(len(plaintext)):
        KEY = secrets.randbelow(255) + 1
        secretkey.append(str(KEY))
    write_txt2('移位密钥', secretkey)
    return secretkey

# 加密
def encrypt(plaintext,secretkey):
    ciphertext = []
    for (i,j) in zip(plaintext,secretkey):
        # map根据提供的函数对指定序列做映射
        list_rt = list(map(ord, i))
        for k in range(len(list_rt)):
            a = list_rt[k]
            a += int(j)
            if a > 256:
                a -= 256
            list_rt[k] = a
        list_rt = map(chr, list_rt)
        list_rt = ''.join(list_rt)
        ciphertext.append(list_rt)
    write_txt2('移位密文', ciphertext)
    return ciphertext

# 解密
def unencrypt(ciphertext, secretkey):
    recover = []
    for (i,j) in zip(ciphertext,secretkey):
        # map根据提供的函数对指定序列做映射
        list_rt = list(map(ord, i))
        for k in range(len(list_rt)):
            a = list_rt[k]
            a -= int(j)
            if a > 256 or a < 0:
                a += 256
            list_rt[k] = a
        list_rt = map(chr, list_rt)
        list_rt = ''.join(list_rt)
        recover.append(list_rt)
    return recover

if __name__ == "__main__":
    name='移位明文'
    path = os.getcwd()+"\\"+name+".txt"
    plaintext = read_txt2(path)
    print('明文:', plaintext)
    secretkey = pro_secretkey2(plaintext)
    print('密钥:', secretkey)
    ciphertext = encrypt(plaintext, secretkey)
    print('密文:', ciphertext)
    recover = unencrypt(ciphertext, secretkey)
    print('解密结果:', recover)

运行截图

 如果对你有帮助,开源不易,请多支持点赞

  • 8
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

起当风萧

如果喜欢请支持一下~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值