python实现凯撒加密和暴力破解凯撒加密(源码及运行结果截图)


原理太简单就不赘述了!

一、凯撒加密(源码)

plaintext = input("请输入明文(小写):\n")#输入明文
key = int(input("请输入密钥(0~25):\n"))#输入明文

plaintext= str.upper(plaintext)#都换成大写
ciphertext=''

for x in plaintext:
    #空格还输出空格,将输出默认换行去掉
    if(x==' '):
        ciphertext=ciphertext+' '
        
    #ord()函数返回对应字符的ascii码,chr()表示ascii码对应的字符
    #需要拐回头
    elif(ord(x)-ord('A')+key >= 26 ):
        ciphertext=ciphertext+chr(ord(x)-26+key)
        
    #不需要
    else:
        ciphertext=ciphertext+chr(ord(x)+key)

#输出密文
print ("密文为:",ciphertext)

二、暴力破解凯撒加密(源码)

ciphertext = input('请输入密文(小写):\n ')
ciphertext = str.upper(ciphertext)

print("所有可能的明文为:")
for key in range(0,26):#依次尝试26个密钥
    plaintext=''
    
    for x in ciphertext:
        
        if(x==' '):
            plaintext=plaintext+' '
            
        elif(ord(x)-ord('A')-key<0):
            plaintext=plaintext+chr(ord(x)-key+26)
        
        else:
            plaintext=plaintext+chr(ord(x)-key)

    print ("(key=",key,"):",plaintext)

三、运行结果截图

在这里插入图片描述
![在这里

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值