简体   繁体   English

我将如何在python中实现vigenere密码

[英]How would I implement the vigenere cipher in python

I was tasked to create a caesar cipher in the past and now I am trying to implement the viginere cipher in python. 我过去曾受过创建凯撒密码的任务,现在我正尝试在python中实现viginere密码。 I want to know how I would go about doing this. 我想知道我将如何去做。 I have a basic idea of using variables from the user as 'plaintext' and the alphabet as its own variable and then adding them to create its own variable and using the index from these in the alphabet and the line of code: 我有一个基本的想法,将来自用户的变量用作“纯文本”,并将字母用作其自己的变量,然后将其添加以创建自己的变量,并使用字母和代码行中的这些变量的索引:

cipher += alphabet[(alphabet.index(c)+key) % (len(alphabet))

This perhaps may be wrong. 这也许是错误的。

The following comes from Rosetta Code 's web site: 以下来自Rosetta Code的网站:

from itertools import starmap, cycle

def encrypt(message, key):

    # convert to uppercase.
    # strip out non-alpha characters.
    message = filter(lambda _: _.isalpha(), message.upper())

    # single letter encrpytion.
    def enc(c,k): return chr(((ord(k) + ord(c)) % 26) + ord('A'))

    return "".join(starmap(enc, zip(message, cycle(key))))

def decrypt(message, key):

    # single letter decryption.
    def dec(c,k): return chr(((ord(c) - ord(k)) % 26) + ord('A'))

    return "".join(starmap(dec, zip(message, cycle(key))))

An example showing how to use the code is included: 包括一个显示如何使用代码的示例:

text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
key = "VIGENERECIPHER"

encr = encrypt(text, key)
decr = decrypt(encr, key)

print text
print encr
print decr

Finally, we can see what output of running the code should be: 最后,我们可以看到运行代码的输出应该是:

Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM