Answer to Question #346018 in Python for Nir

Question #346018

Cipher with Key





A Keyword Cipher is a monoalpha





uses a key to provide en ption





In a substitution cipher each letter of





matched with a different letter accord to phetet





Using these letter matchings, every letter of the esse





substituted to get the encrypted messag





In a keyword cipher, the key determines the let he ciphertext alphabet is created by keeping the lette the beginning (after removing the repeated letters then the rest of remaining letters are used in aph





For example, if the key is zebras





Plaintext Alphabet: albicidjeifigibili Ciphertext Alphabet : zjelb/r/als/cidition





Notice that with this key, we are able to match each lecer of engl alphabet with a different letter. Using these matchings we can encrypt the word discovered as rpbluacerda





replaced with f,i is replaced with and soon





Given a key K and the message M, encrypt the message Keyword Cipher, using the given key





Input





The first tine contains two

1
Expert's answer
2022-05-30T15:14:54-0400
def cipherDictionary(key):  # case sensetive version
    alphabet = "ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz,.-!?"
    cipherDict = dict()
    cipherDict[" "] = " " #remain spaces
    added = set()
    i = 0
    for letter in alphabet:
        index = ord(key[i])%len(alphabet)   # ord() gets the ASCII number of a letter in key
        while(index in added):
            index = ( index+5 )%len(alphabet)
        added.add(index)
        cipherDict[letter] = alphabet[index]
        i = (i+1)%len(key)  #move to next letter in key
    return cipherDict
    
def encrypt(text, key):
    cipher = cipherDictionary(key)
    encrypted = ""
    for i in text:
        encrypted+=(cipher[i])
    return encrypted


def decrypt(text, key):
    decipher = {v: k for k, v in cipherDictionary(key).items()}
    decrypted = ""
    for i in text:
        decrypted+=(decipher[i])
    return decrypted


while True:
    print("Encrypt - 1, dectypt - 2, exit - q: ")
    mode = input()
    if(mode == 'q'):
        break
    if(mode!='1'and mode!='2'):
        continue


    print("Enter the message: ")
    message = input()
    print("Enter the keywoard: ")
    keyword = input()
    if (mode == '1'):
        print(encrypt(message,keyword) )
    elif (mode == '2'):
        print(decrypt(message,keyword) )

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS