Vigenere的加密和解密、破解

- 工具:Anaconda3,python3.5

实验一、 维吉尼亚密码的加密和解密

  • 维吉尼亚密码(又译维热纳尔密码)是使用一系列凯撒密码组成密码字母表的加密算法,属于多表密码的一种简单形式。

加密

def encrypt(message,key):#加密
    cipher = ''
    non_alpha_count = 0
    for i in range (len(message)):#遍历
        if message[i].isalpha():
            if message[i].islower():
                offset = ord(key[(i - non_alpha_count) % len(key)]) - ord('a')
                cipher += chr((ord (message[i]) - ord('a') + offset) % 26 + ord('a'))
            else:
                offset = ord(key[(i - non_alpha_count) % len(key)]) - ord('a')
                cipher += chr((ord (message[i]) - ord('A') + offset) % 26 + ord('A'))        
        else:
            cipher += message[i]
            non_alpha_count += 1
    return cipher
  • 测试
message = 'Figure out number of sectors to read'
key = 'quick'
print (encrypt(message,key))

在这里插入图片描述

解密

def decrypt(cipher,key):#解密
    message = ''
    non_alpha_count = 0
    for i in range (len(cipher)):#遍历
        if cipher[i].isalpha():
            if cipher[i].islower():
                offset = ord(key[(i - non_alpha_count) % len(key)]) - ord('a')
                message += chr((ord (cipher[i]) - ord('a') - offset) % 26 + ord('a'))
            else:
                offset = ord(key[(i - non_alpha_count) % len(key)]) - ord('a')
                message += chr((ord (cipher[i]) - ord('A') - offset) % 26 + ord('A'))        
        else:
            message += cipher[i]
            non_alpha_count += 1
    return message
  • 测试
cipher = 'Vcowbu icv xkgjgb ez agmjizu de lmcn'
key = 'quick'
print (decrypt(cipher,key))

在这里插入图片描述
可以证明,加密和解密方式是正确的!

最后,封装

##########Vigenere密码############

#加密函数
def encrypt(message,key):#加密
    cipher = ''
    non_alpha_count = 0
    for i in range (len(message)):#遍历
        if message[i].isalpha():
            if message[i].islower():
                offset = ord(key[(i - non_alpha_count) % len(key)]) - ord('a')
                cipher += chr((ord (message[i]) - ord('a') + offset) % 26 + ord('a'))
            else:
                offset = ord(key[(i - non_alpha_count) % len(key)]) - ord('a')
                cipher += chr((ord (me
  • 6
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值