Python实现维吉尼亚密码加解密

本文详细介绍了如何使用Python实现维吉尼亚密码的加密和解密过程,通过实例代码展示了该经典密码学技术的应用,适合对密码学和Python编程感兴趣的读者学习。
摘要由CSDN通过智能技术生成
明文:"Common sense is not so common."
密钥:"PIZZA"
密文:"Rwlloc admst qr moi an bobunm."
说明:表格中的字母都是大写,在输入输出时可以进行大小写转换,使得加解密前后明文和密文相同位置的字母大小写一致。
如果用数字0-25代替字母A-Z,维吉尼亚密码的加密文法可以写成同余的形式:
加密:Ci = (Pi + Ki ) mod 26
解密:Pi = (Ci - Ki )mod 26
其中Pi 是原文字母下标,Ci是密文字母下标,Ki是密钥字母下标。原文,密文以及密钥的关系如下图所示:

源代码贴上来:
import string,os
from itertools import cycle # 代码写在这里

def vigenereEncrypt(message,key):
    size = len(key)
    result = []
    cnt = 0
    for i in message:
        if i.upper() in strin
  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用Python实现维吉尼亚密码加解密的完整示例代码: ``` def encrypt_vigenere(plaintext, keyword): """ 使用维吉尼亚密码加密明文。 """ ciphertext = "" keyword = keyword.upper() keyword_len = len(keyword) for i in range(len(plaintext)): char = plaintext[i] if char.isalpha(): keyword_index = i % keyword_len keyword_char = keyword[keyword_index] shift = ord(keyword_char) - 65 if char.isupper(): ciphertext += chr((ord(char) + shift - 65) % 26 + 65) else: ciphertext += chr((ord(char) + shift - 97) % 26 + 97) else: ciphertext += char return ciphertext def decrypt_vigenere(ciphertext, keyword): """ 使用维吉尼亚密码解密密文。 """ plaintext = "" keyword = keyword.upper() keyword_len = len(keyword) for i in range(len(ciphertext)): char = ciphertext[i] if char.isalpha(): keyword_index = i % keyword_len keyword_char = keyword[keyword_index] shift = ord(keyword_char) - 65 if char.isupper(): plaintext += chr((ord(char) - shift - 65) % 26 + 65) else: plaintext += chr((ord(char) - shift - 97) % 26 + 97) else: plaintext += char return plaintext ``` 该代码包含两个函数:`encrypt_vigenere()`用于加密明文,`decrypt_vigenere()`用于解密密文。两个函数都接受两个参数:明文或密文(plaintext或ciphertext)和关键字(keyword)。 示例用法: ``` plaintext = "HELLO WORLD" keyword = "SECRET" ciphertext = encrypt_vigenere(plaintext, keyword) print(ciphertext) # 输出:"DPLLR XPLRH" decrypted_plaintext = decrypt_vigenere(ciphertext, keyword) print(decrypted_plaintext) # 输出:"HELLO WORLD" ``` 注意:在使用维吉尼亚密码进行加密时,关键字应该是不易猜测的,否则加密的安全性会受到影响。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Wzying233

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

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

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

打赏作者

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

抵扣说明:

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

余额充值