简单的维吉尼亚密码加密解密python示例代码

本文介绍了维吉尼亚密码,一种基于凯撒密码的多表加密算法,详细解释了如何使用大写字母进行加密和解密操作,并提供了Python代码示例。
摘要由CSDN通过智能技术生成

       维吉尼亚密码(又译维热纳尔密码)是使用一系列凯撒密码组成密码字母表的加密算法,属于多表密码的一种简单形式。相关描述可以看百度百科,个人认为比较全面详尽。

此处给出我的代码(大概会存在一些变量命名的不规范)

 需注意明文与密钥应全部使用大写字母(因为给出的字母表中全是大写字母)

alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'


def encode():
    default = input('input your contents here:')
    key = input('input your key here:')
    cipher = ''
    for i in range(len(default)):
        cipher += alphabet[(alphabet.find(default[i]) + alphabet.find(key[i % len(key)])) % 26]
    print('the encrypted text is:', cipher)


def decode():
    key = input('input the key here:')
    cipher = input('input the encrypted text:')
    real = ''
    for i in range(len(cipher)):
        real += alphabet[(alphabet.find(cipher[i]) - alphabet.find(key[i % len(key)])) % 26]
    print('the decoded text is:', real)


while True:
    choice = input('1.encode; 2.decode; 0.quit\n')
    if choice == '1':
        encode()
    elif choice == '2':
        decode()
    else:
        print('quit successfully!')
        break
  • 按1输入对应的要加密的文本与密钥(key)可以进行加密
  • 按2输入对应要解密的文本与密钥可以进行解密
  • 按0结束循环

有问题诚恳请求大家指出改正。

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值