问题
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)
回答1:
Your error can be observed by looking at this line:
def enc(c,k): return chr(((ord(k) + ord(c)) % 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...
来源:https://stackoverflow.com/questions/28771396/python-filter-lambda