Errata
Errata

Reputation: 71

How to make a reverse function decrypt for my encrypt function

This is the encrypt function and it works well

def encrypt(password):
    for i in (password):
        print(dict_Chiper[i])
        not_Encrpyted = ''.join(dict_Chiper[i] for i in password)
        Encrpyted = ''.join(reversed(not_Encrpyted))
    print(Encrpyted)
    return Encrpyted

This is the inverse dictionary I make in respect to dict_Chiper for encrypting

dict_Dechiper = {v: k for k, v in dict_Chiper.items()}

This is the faulty function. Is it also faulty in the dictionary? Should I make the dictionary manually?

def decrypt(password):
    not_Decrypted = reversed(password.split('\n', 12))
    print(not_Decrypted)
    Decrypted = ''.join(dict_Dechiper[j] for j in (not_Decrypted))
    print(Decrypted)
    return

Upvotes: 1

Views: 897

Answers (1)

Victor Moura
Victor Moura

Reputation: 71

Considering your password = "abcabc" and dict_Chiper = {"a":"b", "b":"c", "c": "d", "d":"a"}, the ciphered result would be "dcbdcb" and, without any changes, your decrypting code ends up throwing an exception: KeyError: 'dcbdcb'.

This is because reversed(password.split('\n', 12)) is returning a list_reverseiterator object that won't actually iterate over the string you are trying to decrypt. Instead, it is iterating over a list that looks like ['dcbdcb']. That's why it threw the key error.

To fix it, I removed the split statement, created a string from the reverse iterator and, to keep things consistent, returned the decrypted password:

def decrypt(password):
    not_Decrypted = ''.join(reversed(password))
    Decrypted = ''.join(dict_Dechiper[j] for j in (not_Decrypted))
    return Decrypted

And, because of the '\n' split, one can assume that you want to decrypt a string containing multiple passwords separated by \n. That would require a few changes:

def decrypt(password):
    not_Decrypted_list = [''.join(reversed(each_password)) for each_password in password.split('\n', 12)]
    not_Decrypted = '\n'.join(not_Decrypted_list)
    Decrypted = ''.join(dict_Dechiper[j] for j in (not_Decrypted))
    return Decrypted
  • not_Decrypted_list: list with reversed encrypted passwords that were separated by '\n'.
  • not_Decrypted: a string containing not_Decrypted_list elements separated by '\n'

Notice that there must be a '\n': '\n' mapping in your dict_Dechiper. Otherwise, it will throw a KeyError: '\n'

Upvotes: 2

Related Questions