问题描述
尝试创建一个关键字密码和Ive遇到这个,我知道它使字符串大写,并删除像空格逗号和括号的东西。我尝试删除它,我的代码不工作,我只想知道如何成功地将其删除
Trying to create a keyword cipher and Ive come across this,I know that it makes the string upper case and remove things like spaces commas and parentheses.I've tried removing it and my code doesnt work, I just want to know how I can remove this successfully
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))))
text = input("Enter the message you want to crypt: ")
key = input("Enter the key you would like to use: ")
encr = encrypt(text, key)
decr = decrypt(encr, key)
print (text)
print (encr)
print (decr)
推荐答案
可以通过查看这一行来观察错误:
Your error can be observed by looking at this line:
def enc(c,k): return chr(((ord(k) + ord(c)) % 26) + ord('A'))
此功能利用字符代码加密结果。由于它使用模26,并添加 ord('A')
,它专门用于大写字母。如果您不介意不可读加密字符串,则重写加密/解密的一种方法是:
This function exploits character codes to encrypt the result. Since it uses modulo 26, and adds ord('A')
it is specialized for upper case letters. One way to rewrite the encryption/decryption if you don't mind unreadable encrypted strings is:
from itertools import cycle
def encrypt(message,key):
def encryptLetter(letterKey):
letter,key=letterKey
return chr(ord(letter)+ord(key))
keySeq=cycle(key)
return "".join(map(encryptLetter,zip(message,keySeq)))
def decrypt(message,key):
def decryptLetter(letterKey):
letter,key=letterKey
return chr(ord(letter)-ord(key))
keySeq=cycle(key)
return "".join(map(decryptLetter,zip(message,keySeq)))
显然这不安全在所有...
Obviously this isn't secure at all...
这篇关于Python过滤器/ lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!