Fluffy Fluffy - 7 months ago 22
Python Question

Increasing the number of iterations make the result of a polymorphic "encryption" slightly different

For a random project, I'm writing a python program that randomly generates "encryption" and "decryption" routines for strings. The resulting routines are mean to be used in

eval()


def buildRoutines(routine_len):
instructions = ['+', '-', '^']
pairs = {'+': '-', '-': '+', '^': '^'}
encrypt = ""
decrypt = ""
random.seed()
for _ in range(0, routine_len):
i = random.randrange(3)
j = random.randrange(100)
encrypt += 'e=' + 'chr((' + 'ord(e)' + instructions[i] + str(j) + ')%255)' + ';'
decrypt = 'e=' + 'chr((' + 'ord(e)' + pairs[instructions[i]] + str(j) + ')%255)' + ';' + decrypt
# Do some more stuff
encrypt = 'a="";e=""\nfor b in c:e=b;' + encrypt + 'a+=e;'
decrypt = 'd="";e=""\nfor b in a:e=b;' + decrypt + 'd+=e;'
return {'encrypt': encrypt, 'decrypt': decrypt}


Up to around 50-ish iterations works fine (routine_len), but when I go above that, the result is slightly off the original string. The more iterations, the more different it is. At 150 iterations, just one or two characters are wrong.

I've been trying to figure this out, but I can't seem to fix it. It's just probably something really stupid that I'm missing.

EDIT: The value I was using to mod was wrong. Thank you everyone who replied.

Answer

With %255, your max value isn't 255, it's 254. Use %256 instead.