## Is there a way to reverse the processing of a specific function?

Felipe Hernández :

I've been writing a small "encryption" program for a homework, but although it can encrypt a given String easily, I just cannot figure out how to perform decryption of the resulting string. The encryption function goes as follows:

``````char_set = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','ñ','o','p','r','s','t','u','v','w',
'x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','Ñ','O','P','Q','R','S','T','U',
'V','W','X','Y','Z','1','2','3','4','5','6','7','8','9','0',' ','.',',']
char_set.reverse()
cypherText = ''

def encrypt(msg):
global char_set, cypherText
shifts = len(msg)**2**2
d = {}
for i in range(len(char_set)):
letter = char_set[i]
shifted_letter = char_set[(i + shifts) % len(char_set)]
d[letter] = shifted_letter
for letter in msg:
if letter in char_set:
letter = d[letter]
cypherText += letter
else:
cypherText += letter
return cypherText
``````

Is there a native way to reverse the processing this function is doing, or does any of you have a suggestion on how to "reverse engineer" this code?

blhsing :

Since all the encryption does is to rotate the character mapping by a certain offset, the decryption would only need to rotate the mapping in the opposite direction; that is, change:

``````shifted_letter = char_set[(i + shifts) % len(char_set)]
``````

to:

``````shifted_letter = char_set[(i - shifts) % len(char_set)]
``````

for the decryption function and it will work:

``````def decrypt(cypherText):
msg = ''
shifts = len(cypherText)**2**2
d = {}
for i in range(len(char_set)):
letter = char_set[i]
shifted_letter = char_set[(i - shifts) % len(char_set)]
d[letter] = shifted_letter
for letter in cypherText:
if letter in char_set:
letter = d[letter]
msg += letter
else:
msg += letter
return msg
``````

so that:

``````print(decrypt(encrypt('Hello, world!')))
``````

outputs:

``````Hello, world!
``````

### Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19539&siteId=1
Recommended
Ranking
Daily