凯撒密码与python实现

凯撒密码与python实现

目录

1.凯撒密码

凯撒密码作为一种最为古老的对称加密体制,在古罗马的时候都已经很流行,他的基本思想是:通过把字母移动一定的位数来实现加密和解密。明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推X将变成A,Y变成B,Z变成C。由此可见,位数就是凯撒密码加密和解密的密钥。

Let k, x, y ε {0,1, …, 25}
• Encryption: y = ek(x) ≡ x + k mod 26
• Decryption: x = dk(x) ≡ y - k mod 26


2.python实现

代码块语法遵循标准python3:

@binbin_Erices@163.com
'''en_decrypt.py'''
#把加密明文全部转化为小写
def toAlpha(c,i):
    c = c.lower()
    num = ord(c)
    if num >= 97 and num <= 122:
        num = 97 + ((num - 97) + i) % 26
    return chr(num)

#string 明文  i 移位参数
def encrypt(string,i):
    string_new = ''
    for s in string:
        string_new += str(toAlpha(s,i))
    print(string_new)
    return string_new

#string 密文  i 移位参数
def decrypt(string,i):
    encrypt(string,-i)

'''main.py'''
from en_decrypt import *

def main():
    test = input("请输入明文:")
    num = input("请输入移位个数:")
    num = int(num)
    encode = encrypt(test,num)
    decrypt(encode,num)

if __name__ == "__main__":
    for i in range(3):
        main()

3.代码执行结果

请输入明文:python
请输入移位个数:12
bkftaz
python
请输入明文:hello world
请输入移位个数:8
pmttw ewztl
hello world
请输入明文:Life is short,you need python
请输入移位个数:24
jgdc gq qfmpr,wms lccb nwrfml
life is short,you need python

Process finished with exit code 0

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Erice_s

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值