so I came across the following string encoding method in python.
def encode(the_string):
encoded_string = ''
rotations = ord(the_string[-1]) + 5
for i in range(0, len(the_string)):
value = ord(the_string[i])
for j in range(0, rotations):
value -= 1
if value < 65:
value = 25 + value
encoded_string += chr(value)
rotations += ord(the_string[i])-2
return encoded_string
It looks like a Caesar Cipher where ASCII value of the letter determines the number of shifts of the alphabet, however 'Z' stays at the end. The initial number of rotations is the ASCII value of the last letter of the string plus 5.
def encode(the_string):
ALPHABET='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encoded_string = ''
rotations = (ord(the_string[-1]) + 5) % 25
for i in range(0, len(the_string)):
alphabet_rotate = ALPHABET
print('Rots:',rotations)
for j in range(0, rotations):
alphabet_rotate = alphabet_rotate[1:-1] + alphabet_rotate[0] + alphabet_rotate[-1]
encoded_string += ALPHABET[alphabet_rotate.index(the_string[i])]
rotations += (ord(the_string[i]) - 2)
rotations %= 25
return encoded_string
I am trying to write a decoding method however I am struggling to find the the correct offsets for the rotations. I am reversing the direction of the shifts. Also the lookup of the decoded letter works in reverse. Is this the correct approach? Any help will be appreciated.
def decode(the_string):
ALPHABET='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
decoded_string = ''
rotations = (ord(the_string[-1]) + 3) % 25 # <== 1. PROBLEM HERE
for i in range(0, len(the_string)):
alphabet_rotate = ALPHABET
for j in range(0, rotations):
alphabet_rotate = alphabet_rotate[-2] + alphabet_rotate[0:-2] + alphabet_rotate[-1]
decoded_string += alphabet_rotate[ALPHABET.index(the_string[i])]
rotations += (ord(the_string[i]) +20 ) # <== 2. PROBLEM HERE
rotations %= 25
return decoded_string