pythonencryptionencode

Vigenere Cipher Decryption Issues


key = "password"
def cipher(text): #my example cipher method
    encoded_chars = []
    for i in range(len(text)):
        key_c = key[i % len(key)]
        encoded_c = chr(ord(text[i]) + ord(key_c) % 256)
        encoded_chars.append(encoded_c)
    encoded_string = ''.join(encoded_chars)
    return (encoded_string)


def decipher(text):
    dec = []
    text = base64.urlsafe_b64encode(b"'{text}'").decode()
    print('text')
    for i in range(len(text)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + ord(text[i]) - ord(key_c)) % 256)
        dec.append(text)
    return str(dec_c)
    enter code here
print(decipher("test"))

After encrypting it successfully with vigenere cipher I get something like this: b'\xc2\xbd\xc2\xb8\xc3\x83\xc3\x80' I would like to decrypt this string with the code above and turn it into back to the text "password" however when I try to decrypt my text it leaves me with another encoded string. Can someone explain what I am doing wrong with my decryption?


Solution

  • It's not clear what you are trying to do with the base64 library. Also, you are mixing up come variables in your decrypt method:

        dec.append(text) # text is the passed in argument.
                         # Why append it to the result
    return str(dec_c)    # this is the last element in the loop
                         # why return this rather than the list you made above?
    

    Neither of the above things make much sense. Maybe something like this will get it going in the right direction:

    key = "password"
    def cipher(text): #my example cipher method
        encoded_chars = []
        for i in range(len(text)):
            key_c = key[i % len(key)]
            encoded_c = chr(ord(text[i]) + ord(key_c) % 256)
            encoded_chars.append(encoded_c)
        encoded_string = ''.join(encoded_chars)
        return (encoded_string)
    
    
    def decipher(text):
        dec = []
        for i in range(len(text)):
            key_c = key[i % len(key)]
            dec_c = chr((256 + ord(text[i]) - ord(key_c)) % 256)
            dec.append(dec_c)
        return "".join(dec)
    
    plain = "some text to encrypt"
    
    encrypted = cipher(plain)
    print("encrypted: ", encrypted)
    
    decrypted = decipher(encrypted)   
    print("decrypted: ", decrypted)
    

    Prints:

    encrypted:  ãÐàØã×ÜäçâÔàÇâÚãç
    decrypted:  some text to encrypt